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

时间:2019-11-26 12:27:45

标签: angular components angular7 angular8 angular-dynamic-components

我有一个公共组件,单击按钮时可以将其导入。

在该组件中,有一些通用的HTML:Stackblitz

当我单击按钮时,它会引发以下错误:

  

错误:无法读取未定义的属性'createComponent'

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>

2 个答案:

答案 0 :(得分:3)

尝试:

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

Working Demo

答案 1 :(得分:1)

这是您的分叉StackBlitz link

更改此行

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

有关更多参考,请参阅此StackOverFlow Link