Angular2: how to get ViewChild link in child component

I have a component ( App) that contains another component ( Comp). Appgets string content from the database and forwards it using @Input()c Comp. This string content may contain html tags such as

Some text before <a>Click</a> Some Text after

It is Compassumed that this content will be displayed, and it is assumed that some event listeners will be added. To do this, this content is added using [innerHtml]. Since it (click)is deleted in [innerHtml], a tag reference is required a, and it is assumed that the event listener is added with addEventListener. But I can’t find a way to refer to the tag a, because it ElementRefdoes not contain the component nativeElement.

What is the best way to run this plunker? https://plnkr.co/edit/xVUu0LJ02YVnBO25Zr4j?p=preview

+4
source share
2 answers

Direct access to the DOM is not recommended in Angular2

.

comp :

document.querySelector('body').addEventListener('click', function(event) {
      if (event.target.tagName.toLowerCase() === 'a') {
         that.updateCounter.next(true);
      }
    });

EventEmitter .

Plunker: https://plnkr.co/edit/vm44niH781j4mEQHDpLU?p=preview

+1

Angular2 , /.

"a" "Comp".

Comp @Output() ( EventEmitter),

EventEmitter .

:

Comp:

@Output myClickEventEmitter: EventEmitter

aTagClickHandler (e) {
    myClickEventEmitter.emit(e)
}

:

myCompClickHandler(e) {
    console.log(e);
}

, , .

:

, #variableName :

:

<a #variableName > </a> 

:

@ViewChild('variableName') myATag;
0

Source: https://habr.com/ru/post/1671356/


All Articles