我有一个可以在单击按钮时导入的通用组件。
在该组件中有一些常见的 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>