是否可以手动实例化角度2中的组件 [英] Is it possible to manually instantiate component in angular 2
本文介绍了是否可以手动实例化角度2中的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在角度2中,是否可以手动实例化组件A,然后将其传递并渲染到组件B的模板中?
In angular 2, is it possible to manually instantiate a component A, then pass it around and render in the template of component B?
推荐答案
是的,受支持.您需要一个ViewComponentRef
,例如,可以通过将其注入到构造函数中或使用@ViewChild('targetname')
查询来获取它,并且还可以注入一个ComponentResolver
.
Yes, that's supported. You need a ViewComponentRef
that can for example be acquired by injecting it to the constructor or using a @ViewChild('targetname')
query and a ComponentResolver
that also can be injected.
来自 https://stackoverflow.com/a/36325468/217408 的此代码示例允许添加组件用*ngFor
This code example from https://stackoverflow.com/a/36325468/217408 allows for example to add components dynamically with *ngFor
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
这篇关于是否可以手动实例化角度2中的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文