我有一个公共组件,单击按钮时可以将其导入。在该组件中有常见的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>
尝试一下:
...
@ViewChild('appenHere', {read : ViewContainerRef}) target: ViewContainerRef;
private componentRef: ComponentRef<any>;
...