angularangular-animationsngx-toastr

How to make Angular animation working properly


I'm using ngx-toastr (uses angular/animations) to show toasts. If I trigger them from event created manually then I have significant delay in animation.

  export class AppComponent {
      @ViewChild('iframeElement') iframeElement: ElementRef;
      html = `<!DOCTYPE html><html lang="en"><head><title></title></head><body><div>2. Step 2</div><ul><li>Wait when toast is gone</li><li>Click here 3 times quickly</li><li>Wait few seconds to see toasts</li></ul></body></html>`;

      constructor(private toastr: ToastrService,
                  private renderer: Renderer2) {
      }

      load(e) {
        console.log('Iframe Loaded');
        const iframe = this.iframeElement.nativeElement;

        this.renderer.listen(iframe.contentDocument, 'click', (e) => {
          e.preventDefault();
          console.log('Iframe body clicked', e, e.target);
          this.showMessage('Message From Iframe');
        });
      }

      showMessage(message: string) {
        this.toastr.success(message);
      }
  }

And template:

<button type="button" (click)="showMessage('Just a message')">1. Press Me</button>

<div>
  <iframe #iframeElement src="about:blank" (load)="load($event)" [srcdoc]="html" frameborder="1"></iframe>
</div>

I can see that toasts are added to DOM immediately but they show up in a few seconds after adding to DOM.

Here is the demo


Solution

  • The events which come from iframe are handled outside of Angular zone. You should be handling them inside:

    import { NgZone } from '@angular/core';
    
    constructor(...private ngZone: NgZone) {}
    
    load(e) {
      ...
    
      this.renderer.listen(iframe.contentDocument, 'click', (e) => {
        ...
        this.ngZone.run(() => this.showMessage('Message From Iframe'));
        ^^^^^^^^^^^^^^^^^^
      });
    }
    

    Forked Stackblitz