Angular 2 Only define ViewChild if *ngIf evaluates true

1.2k views Asked by At

How can I only define a view child if it exists in template. I'm using a dynamic component loader like this ...

viewContainer.directive.ts

@Directive({
  selector: '[viewContainer]'
})
export class ViewContainer {
  constructor(public viewContainerRef: ViewContainerRef) {}
}

part of the component.ts

@ViewChild(ViewContainer)
private viewContainer: ViewContainer;

private _postalMapComponent: any;

private set postalMapComponent(component: any) {
  if(!component) {
    return
  }

  let factory = this.resolver.resolveComponentFactory(component);

  let viewContainerRef = this.viewContainer.viewContainerRef;
  viewContainerRef.clear();

  if(this._postalMapComponent)
    this._postalMapComponent.destroy();

  this._postalMapComponent = viewContainerRef.createComponent(factory);
}

private get postalMapComponent(): any {
  return this._postalMapComponent;
}

This works fine using

<ng-template viewContainer></ng-template>

inside the template html file.

If I use something like this in the template ...

<div *ngIf="something">
  <ng-template viewContainer></ng-template>
</div>

... and something evaluates false I run into an undefined error

undefined is not an object (evaluating 'this.viewContainer ...

How could I solve this? Is there a way to only set the ViewChild in the component if it exists in the template?

0

There are 0 answers