0

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

在该组件中有一些常见的 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!
  }  
}

新的tile.component.html:

<p>This is new</p>
4

2 回答 2

4

尝试这个 :

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

工作演示

于 2019-11-26T12:32:00.203 回答
1

这是您的分叉StackBlitz 链接

更改此行

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

有关更多参考,请参阅此StackOverFlow 链接

于 2019-11-26T12:34:33.920 回答