Reputation: 438
We are Looking for a way to subscribe to the src (url) change from an IFrame inside an Angular 7 Application. Is there a way to intercept the src Change?
Upvotes: 4
Views: 6030
Reputation: 1109
Actually it's simpler than you think, and you don't even need fromEvent
and rxjs
.
Just listen to the load
event like this:
<iframe [src]="src" (load)="test()"></iframe>
This is a working Stackblitz
And if you want the iframe reference you can easily get it also without ViewChild:
<iframe #frame [src]="src" (load)="test(frame)"></iframe>
Upvotes: 7
Reputation: 715
You can use the RxJS fromEvent constructor to take the 'load' event from the iFrame and subscribe to its changes. You can use the RxJS skip operator to ignore the initial load event if you need to.
Here's the gist of what you can do, but I've linked a full stackblitz example at the bottom of the answer too.
@ViewChild('iframe') iframe: ElementRef;
ngAfterViewInit(): void {
fromEvent(this.iframe.nativeElement, 'load')
// Skip the initial load event and only capture subsequent events.
.pipe(skip(1))
.subscribe((event: Event) => console.log(event.target));
}
Skip Docs: https://www.learnrxjs.io/operators/filtering/skip.html
From Event Docs: https://www.learnrxjs.io/operators/creation/fromevent.html
Full StackBlitz Example: https://stackblitz.com/edit/angular-dxmbgp
Upvotes: 4