title: angular 2 handle click on link inside iframe
body: <p>Is there a way to catch a click on a link inside an <code>iframe</code>?</p>
  
  <pre><code>&lt;iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe"&gt;&lt;/iframe&gt;
  </code></pre>
  
  <p>My iframe component contains just a simple code which subscribes to observable variables.</p>
  
  <pre><code>export class ContentFrameComponent implements OnInit {
      currentFrameUrl: string;
      currentMenuState: boolean;
      @ViewChild('contentFrame') iframe: ElementRef;
  
      constructor(private frameService: ContentFrameService) {        
        this.currentMenuState = true;      
      }
  
      ngOnInit(): void {
        this.frameService.providerCurrentUrl$.subscribe(data =&gt; this.currentFrameUrl = data);
        this.frameService.providerMenuState$.subscribe(data =&gt; this.currentMenuState = data);
      }
  
      ngAfterViewInit() {
        let doc = this.iframe.nativeElement.contentDocument ||this.iframe.nativeElement.contentWindow;
        if (typeof doc.addEventListener !== undefined) {
          console.log("inside if - addEventListener") // Is shown
          doc.addEventListener("click", this.iframeClickHandler, false)
        } else if (typeof doc.attachEvent !== undefined) {
          console.log("inside if - attachEvent ") // Does not show
          doc.attachEvent("onclick", this.iframeClickHandler)
        }
      }
  
      iframeClickHandler(): void {
        console.log("Click test") // Does not show
      }
  }
  </code></pre>
  
  <p>My goal is to to catch click event on <code>iframe</code> link, stop its propagation and set the url of the iframe link using either <code>router.navigate</code> or <code>location.go</code>/<code>location.replaceState</code>. Not sure yet which option is better.</p>
  
  <p>I have no control over the pages loaded inside the <code>iframe</code>. I only know, that the links should contains such <code>url</code> that can be used with my dynamic routes.</p>