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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With