Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: How to get a reference to a ViewChild in a child component

I have a component (App) that contains another component (Comp). App gets string content from a database and forwards it by @Input() to Comp. This string content can contain html tags like

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

In Comp this content is supposed to be rendered and some event listeners are supposed to be added. Therefor this content is added using [innerHtml]. Because (click) is removed in [innerHtml] a reference to the a tag is needed and a event listener is supposed to be added with addEventListener. But I can't find a way to reference the a tag since an ElementRef to a component doesn't contain nativeElement.

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

like image 712
Thomas Sablik Avatar asked Nov 08 '22 01:11

Thomas Sablik


1 Answers

Direct DOM access is discouraged in Angular2

Here's a hacky way to do it with direct dom access.

Define an event listener in the child comp and filter the event:

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

then use an EventEmitter to update the counter.

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

like image 82
eko Avatar answered Nov 14 '22 22:11

eko