EN VI

Angular 16: ElementRef error in Chrome, but not in Firefox?

2024-03-13 16:00:08
How to Angular 16: ElementRef error in Chrome, but not in Firefox

I am rendering a component inside an iframe to print. I have tested it in Firefox, where it works, but a collaborator on the project has pointed out that there are issues in both Google Chrome and Internet Explorer.

The error I'm getting: TypeError: Cannot read properties of undefined (reading 'nativeElement')

The code:

export class CheckoutComponent {
     @ViewChild('iframe', {read: ElementRef, static: false}) iframe: ElementRef | undefined;
     doc: any;

     onLoad() {
          this.doc = this.iframe!.nativeElement.contentDocument ||this.iframe!.nativeElement.contentWindow;
          this.createComponent();
     }

     createComponent() {
          const component = this.viewContainerRef.createComponent(ReceiptComponent);
          component.setInput('order', this.currentOrder);
          component.location.nativeElement.id = 'receipt';
          this.doc.body.appendChild(component.location.nativeElement);
  }
}

In the template, it looks like this:

<iframe #iframe id="iframe" name="iframe" (load)="onLoad()"></iframe>

I am kind of stumped on this since it works in Firefox - I have tried various methods of making it work, but I seem to be getting nowhere. Any help would be much appreciated! :)

Solution:

Chrome and Explorer dispatch the event load in diferent way than FireFox. I suggest (really I don't like so much) enclosed in a setTimeout(()=>{...your code}) in the onLoad functions that you have reference to the "iframe" (or check if iframe and if not enclosed by setTimeout

   onLoad() {
      if (this.iframe){
          this.doc = this.iframe!.nativeElement.contentDocument ||
                     this.iframe!.nativeElement.contentWindow;
          this.createComponent();
      }
      else  //force to check in a new "cycle"
      {
          setTimeout(()=>{
             this.doc = this.iframe!.nativeElement.contentDocument ||
                        this.iframe!.nativeElement.contentWindow;
             this.createComponent();
          })
      }
  }
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login