Angular中ComponentFactoryResolver弃用后ViewContainerRef动态组件创建疑问
搞定Angular里ViewContainerRef.createComponent的参数问题
先搞懂关键概念
你说的“动态子组件”,就是你要动态弹出来的那个错误提示组件——比如你之前用ComponentFactoryResolver创建的ErrorAlertComponent(或者你自己命名的类似组件)。createComponent()要传的就是这个组件的类,不是ViewContainerRef实例,你之前写错参数了。
直接改代码就行
- 先确认组件注册对了:把你的错误提示组件(比如
ErrorAlertComponent)加到对应模块的declarations里,Angular 9+不用加entryComponents,旧版本得加上。 - 修正showErrorAlert方法:
你原来的错误代码:
改成下面这样(假设你的错误提示组件叫hostViewContainerRef.createComponent(hostViewContainerRef);ErrorAlertComponent):showErrorAlert(message: string) { // 先清掉容器里已有的内容,避免重复弹提示 this.hostViewContainerRef.clear(); // 创建动态组件实例,这里传的就是你的错误提示组件类 const componentRef = this.hostViewContainerRef.createComponent(ErrorAlertComponent); // 给组件传错误消息(如果你的组件有message属性的话) componentRef.instance.message = message; // 可选:加个自动关闭逻辑,比如3秒后销毁组件 setTimeout(() => { componentRef.destroy(); }, 3000); }
为啥这么改?
之前用ComponentFactoryResolver是旧写法,Angular 9+之后直接传组件类就行,内部会自动处理组件工厂的创建。比如你之前的旧代码可能是这样:
const factory = this.componentFactoryResolver.resolveComponentFactory(ErrorAlertComponent); const componentRef = this.hostViewContainerRef.createComponent(factory);
现在直接把factory换成组件类就行,省了一步。
要注意的点
- 确保你在auth组件里已经正确注入了指令的
ViewContainerRef,比如:@ViewChild(PlaceholderDirective) set hostPlaceholder(directive: PlaceholderDirective) { this.hostViewContainerRef = directive.viewContainerRef; } private hostViewContainerRef!: ViewContainerRef; - 别忘了把错误提示组件的类导入到
auth.component.ts里,不然会报错找不到。
内容的提问来源于stack exchange,提问作者Miles Winokur
相关产品推荐
相关产品推荐

