@Component({
selector: 'my-cmp',
template: `
<div #target></div>
`
})
export class MyCmp {
@ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef;
render() {
let cmp = Component(metadata)(type);
this.componentResolver.resolveComponent(cmp).then(factory => {
let component = this.target.createComponent(factory, 0, null, null);
});
}
}
我正在尝试将组件加载到ViewContainerRef
。所有documentation表示创建组件后,它会自动加载到DOM中(ViewChild
所在的位置。)但这不会发生。为什么?请帮忙。
答案 0 :(得分:0)
不确定您添加的代码是完整的还是仅仅是其中的一部分,我没有看到ComponentResolver注入到您的构造函数中,也可能是错误,但是resolveComponent
然后阻止没有关闭(缺少{{ 1}})。
)
以下是Plunker!!
希望这会有所帮助!!
答案 1 :(得分:0)
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Dynamicaly Add Elements</h2>
<button (click)="addItem()">add hello</button>
<div #placeholder></div>
</div>
`,
entryComponents: [HelloComponent]
})
export class App {
@ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef;
private componentFactory: ComponentFactory<any>;
constructor(componentFactoryResolver: ComponentFactoryResolver, compiler: Compiler) {
this.componentFactory = componentFactoryResolver.resolveComponentFactory(HelloComponent);
//this.componentFactory = compiler.compileComponentSync(HelloComponent);
}
addItem () {
this.viewContainerRef.createComponent(this.componentFactory, 0);
}
}