Pathik Vejani
Pathik Vejani

Reputation: 4491

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>

Upvotes: 1

Views: 10645

Answers (2)

Bilel-Zheni
Bilel-Zheni

Reputation: 1312

try this :

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

Working Demo

Upvotes: 4

Gaurang Dhorda
Gaurang Dhorda

Reputation: 3387

here is your forked StackBlitz link

change this line

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

for more reference refer this StackOverFlow Link

Upvotes: 1

Related Questions