Angular中ViewContainerRef.createComponent二次调用功能失效问题
动态注入组件二次加载功能失效问题
我将应用拆分为Header、Context和Content三部分,需要根据路由及其他因素向Context组件的ViewContainerRef动态注入其他组件,为此开发了如下代码:
ContextComponent(ViewContainerRef载体)
该组件注入ContextService,用于切换显示的上下文组件:
export class ContextComponent implements OnInit { @ViewChild("contextComponent", {static: true, read: ViewContainerRef}) viewContainerRef!: ViewContainerRef; constructor(private contextService: ContextService) {} ngOnInit(): void { this.contextService.setViewContainerRef(this.viewContainerRef); } }
ContextService实现
export class ContextService { private component!: ComponentRef<any>; private viewContainerRef!: ViewContainerRef; public setViewContainerRef(viewContainerRef: ViewContainerRef): void { this.viewContainerRef = viewContainerRef; } public setComponent<T>(component: Type<T>): ComponentRef<T> { this.viewContainerRef.clear(); this.component = this.viewContainerRef.createComponent<T>(component); return this.component; } public instance<T>(): T { return (this.component as ComponentRef<T>).instance; } }
服务使用示例
setupContext(): void { this.context.setComponent(ClientPersonEditContextComponent); this.context.instance<ClientPersonEditContextComponent>().clientName.set(this.client.firstName + " " + this.client.lastName); }
问题现象
上述代码仅首次调用正常,第二次调用时组件虽已加载到DOM,但功能完全失效,且无控制台报错:
- 首次加载:组件功能正常,交互元素可正常使用
- 二次加载:组件DOM已渲染,但所有交互功能失效,界面无响应
内容的提问来源于stack exchange,提问作者Bruno Miguel
相关产品推荐
相关产品推荐

