Angular 7 TypeError: Cannot read property 'createComponent' of undefined

I am receiving a

TypeError: Cannot read property 'createComponent' of undefined

while trying to load a component dynamically.

import {
  AfterViewInit,
  ViewChild,
  ViewContainerRef,
  Component,
  ComponentFactory,
  ComponentFactoryResolver,
  ComponentRef,
  OnDestroy,
} from '@angular/core';

import { AddFabComponent } from '@app/shared/components/fabs/add-fab/add-fab.component'


@Component({
  selector: 'app-airframe-list',
  templateUrl: './airframe-list.component.html',
  styleUrls: ['./airframe-list.component.scss']
})

export class AirframeListComponent implements AfterViewInit, OnDestroy {

  componentRef: any;
  destroy: any;

   @ViewChild('fabconainter', { read: ViewContainerRef }) fabconainter: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) { }

  ngAfterViewInit() {
    this.createComponent();
  }

  ngOnDestroy() {
    this.componentRef.destroy();
  }

  createComponent() {
      const factory = this.resolver.resolveComponentFactory(AddFabComponent);
      const componentRef = this.fabconainter.createComponent(factory);
  }
}

I've tried different container too (just in case)

<div #fabconainter></div>
<ng-template #fabconainter></ng-template>
<template #fabconainter></template>

I'm at a lost. Any code examples would be appreciated too.

728x90

0 Answers Angular 7 TypeError: Cannot read property 'createComponent' of undefined