Was*_*siF 3 angular dynamic-components
正如您可能知道的,在早期版本的 Angular 中,可以借助ComponentFactoryResolveras创建动态组件
export class DialogService {
dialogComponentRef: ComponentRef<DialogComponent>
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector
) {}
appendDialogComponentToBody() {
// logic to add component using `ComponentFactoryResolver` instance
}
}
Run Code Online (Sandbox Code Playgroud)
但现在ComponentFactoryResolver最新版本已弃用。
是的,有一种方法(到目前为止我知道)我们可以使用以下代码片段创建动态组件
@ViewChild("viewContainerRef", { read: ViewContainerRef }) vcr!: ViewContainerRef;
Run Code Online (Sandbox Code Playgroud)
但同样,这只适用于component,而不适用于service。
任何帮助,将不胜感激。
您应该能够使用createComponent从 导出的函数@angular/core,
const componentRef = createComponent(MyComponent, {
environmentInjector: this.appRef.injector,
})
Run Code Online (Sandbox Code Playgroud)
然后
this.appRef.attachView(componentRef.hostView); // and detach later
Run Code Online (Sandbox Code Playgroud)
你应该很高兴没有viewContainerRef
| 归档时间: |
|
| 查看次数: |
2051 次 |
| 最近记录: |