Search code examples
angularcomponentsangular7angular8angular-dynamic-components

add component on click of button in angular 7/8


I have one common component which can be imported when a button is clicked.

In that component there is some common HTML: Stackblitz

When I click on the button it throws the following error:

Error: Cannot read property 'createComponent' of undefined

app.component.html:

<div class="row" #appenHere></div>

<div>
    <button (click)="addNewComponent()">Append</button>
</div>

app.component.ts:

import { Component, OnInit, TemplateRef, ViewChild, AfterViewInit, Inject, ViewContainerRef, ComponentFactoryResolver, ComponentRef } from '@angular/core';
import { NewTileComponent } from './new-tile/new-tile.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {

  @ViewChild('appenHere') target: ViewContainerRef;
  private componentRef: ComponentRef<any>;

  constructor(private resolver: ComponentFactoryResolver) { }

  addNewComponent() {
    let childComponent = this.resolver.resolveComponentFactory(NewTileComponent);
    this.componentRef = this.target.createComponent(childComponent); // <-- here it's throws an error!
  }  
}

new-tile.component.html:

<p>This is new</p>

Solution

  • try this :

    ...
    @ViewChild('appenHere', {static : false, read : ViewContainerRef}) target: ViewContainerRef;
    private componentRef: ComponentRef<any>;
    ...
    

    Working Demo