单击 angular 中的按钮添加组件 7/8

add component on click of button in angular 7/8

我有一个通用组件,可以在单击按钮时导入。

在该组件中有一些共同点 HTML:Stackblitz

当我点击按钮时,它抛出以下错误:

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>

试试这个:

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

Working Demo

这是你的分叉 StackBlitz link

更改此行

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

有关更多参考,请参阅此