angular新版本动态创建组件
【代码】angular新版本动态创建组件。
·
@Component({
selector: 'a-component',
template: `
<ng-template #dynamicFilterConditionComponent></ng-template>
`
})
export class Acomponent implements OnInit {
// static true表示可以在 完全初始化组件视图之前调用
// read: ViewContainerRef 表明类型
@ViewChild('dynamicComponent', { static: true, read: ViewContainerRef }) dynamicComponent: ViewContainerRef;
componentRef: ComponentRef<any>;
key:string;
//组件map
componentsMap = {
[ConfigTypeKeyEnum.SEARCH_SCOPE]: SearchScopeComponent
};
constructor() {}
ngOnInit(): void {
this.createComponent();
}
createComponent() {
this.clearComponent();
this.componentRef = this.filterComponent.createComponent(this.componentsMap[this.type]);
// 动态组件传值
this.componentRef.instance.key = this.key;
this.componentRef.instance.valueChange.subscribe((query) => {
// 这里用来处理动态创建组件的回调
});
}
clearComponent() {
this.filterComponent.clear();
}
}
更多推荐
所有评论(0)