【发布时间】:2020-02-29 08:46:57
【问题描述】:
我希望构建一个组件,它使用 Angular 的 componentFactoryResolver 和 componentFactory 将组件动态注入 DOM,但使用传入的 viewContainerRef 来确定可注入的内容。
@Component({
selector: 'my-component-loader',
template: ``
})
export class MyComponentLoader implements OnInit {
constructor(private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver,
private componentLoaderService: ComponentLoaderService) {
}
ngOnInit() {
this.componentLoaderService.loadComponent.pipe(
tap((component, componentViewContainerRef) => this.loadComponent(component, componentViewContainerRef))
).subscribe();
}
loadComponent(component, callerViewContainerRef) {
this.viewContainerRef.clear();
const factory = this.componentFactoryResolver.resolveComponentFactory(component);
this.viewContainerRef.createComponent(factory);
}
}
如何在my-component-loader 位置加载组件,逻辑位置来自callerViewContainerRef,以便创建的组件具有可用于callerViewContainerRef 的DI 树。
简而言之,这在方式上类似于 Material 的 MatDialog。
https://github.com/angular/components/blob/master/src/material/dialog/dialog-config.ts
有没有更简单的方法来处理而不复制 Angular CDK 门户逻辑?
** 编辑 **
这就像传入 callerViewContainerRef 的注入器一样简单吗?
this.viewContainerRef.createComponent(factory, 0 , callerViewContainerRef.injector);
【问题讨论】:
标签: angular