Search code examples
javascriptangularoptimizationangular-changedetection

is there any way to listen change detection completed event in angular


I have a component that contains an iframe, but only visible (*ngif) after the http call.

<iframe id="myFrame" [src]="url | sanitizeUrl" *ngIf="showIFrame "></iframe>

Here is the getData method that enables the showIFrame property.

this.getData().subscribe(
  (_response: string) => {
     this.showIFrame = true;
     setTimeout(() => {
         this._listenClickOnIframe();
     }, 100);
});

based on showIFrame iframe is visible.

I have one other method _listenClickOnIframe that add onclick event to iFrame. This method is inside setTimeout with 100ms wait. If I don't use setTimeout the _listenClickOnIframe method gets executed before DOM changes and there is no iFrame on DOM.

Is there any other way to handle this? For some slow machines 100ms (random number of miliseconds) may not be enough, and which I think not a good approach.

I am looking kind of change detection completed event, is there any way or better approach to solve such situations?


Solution

  • You should listen to the load event of the iframe and only start listening then:

    <iframe id="myFrame" [src]="url | sanitizeUrl" *ngIf="showIFrame" (load)="_listenClickOnIframe()"></iframe>
    

    LE:

    For general angular lifecycle practices I recommend reading the documentation here: https://angular.io/guide/lifecycle-hooks .

    The last hook which is called (after rendering) is ngAfterViewChecked but maybe you don't necessarily need this one (using it might affect the performance of your app as it is called pretty often).

    Here is another link explaining different hooks and their uses: https://guide.freecodecamp.org/angular/lifecycle-hooks/