1

I'm learning Angular and attempting to add a component to my HTML programmatically. However, I get the following error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'viewContainerRef' of undefined

The following are the key parts of code.

My Placeholder directive:

import { Directive, ViewContainerRef } from '@angular/core';

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

Main.component.ts:

export class MainComponent implements OnInit {
  @ViewChild(PlaceholderDirective, {static: false, read: ViewContainerRef}) alertHost: PlaceholderDirective;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

  ngOnInit(): void {
    this.showMyComp();
  }

  private showMyComp() {
    const testCmpFactory = this.componentFactoryResolver.resolveComponentFactory(TestComponent);
    const hostViewContainerRef = this.alertHost.viewContainerRef;
    hostViewContainerRef.clear();

    hostViewContainerRef.createComponent(testCmpFactory);
  }
}

Main.component.html:

<ng-template appPlaceholder></ng-template>

I have narrowed the issue down to const hostViewContainerRef = this.alertHost.viewContainerRef; in MainComponent.ts. The problem is that this.alertHost is null but I have been unable to figure out why.

halfer
  • 19,824
  • 17
  • 99
  • 186
sisko
  • 9,604
  • 20
  • 67
  • 139

1 Answers1

1

I know this is an old question, but I had the same issue a few days ago: Method that uses alertHost is invoked from ngOnInit().

To make sure that the references injected by @ViewChild are present, always write initialization code using ngAfterViewInit().

In addition to invoking showMyComp from ngAfterViewIinit, I had to update @ViewChild to following:

@ViewChild(PlaceholderDirective, {static: false}) alertHost: PlaceholderDirective;

(it is possible that this part is caused by different angular version)

ASisic
  • 99
  • 4