Friday, September 13, 2019

How do I get around the inability to monkey with a local reference hidden by *ngIf in and Angular 7 application?

Assuming the ElementRef's nativeElement is conditionally hidden upfront when the view for the template is initialized, the only way to get at it is with a subscription via ViewChildren instead of ViewChild. Otherwise it just reads as undefined after all. To approach things the right way you'll need these imports in your Angular component:

import { ElementRef, ViewChildren, QueryList } from '@angular/core';
import { Subscription } from 'rxjs';

 
 

For this example, shall we pretend #powerBI decorates an iframe html tag in the template making what is known as a local reference? We will need two variables in our component class, but outside of any of its methods, like so:

@ViewChildren('powerBI') powBI: QueryList<ElementRef<HTMLElement>>;
public viewChildrenSubscription: Subscription;

 
 

Here is the magic you have been waiting for:

public showIFrame():void {
   this.isToShowIFrame = true;
   if (this.viewChildrenSubscription) this.viewChildrenSubscription.unsubscribe();
   this.viewChildrenSubscription = this.powBI.changes.subscribe(bi => { bi.forEach(i => {
         i.nativeElement.setAttribute("src", "http://www.tomjaeschke.com");
      });
   });
}

No comments:

Post a Comment