Angular – Add event listener to DOM element in Angular 4

angularangular-dom-sanitizer

I would like to add an event listener to the iframe load event inside an Angular Component.

I know I could use ViewChild decorator and then access the element.nativeElement.addEventListener

However, in order to comply with best practices when dealing with DOM inside Angular, accessing the addEventListener on the nativeElement is still considered platform independent? Or am I binding my app to pure browser app?

Thanks

Best Answer

if you want angular way then I suggest you to create directive like as below and attach it with your dom element

@Directive({
  selector: `[IFrame]`
})
export class IFrameDirective {
  constructor(private el: ElementRef, private renderer: Renderer) { }

  @HostListener('load', ['$event'])
  iFrameLoad(event: Event) {
    alert('IFrame loaded');
  }
}

@HostListener in directive allows you to bind event with host element with which your directive is binded.

html

<iframe IFrame> ..rest code
Related Topic