我希望构建一个组件,该组件使用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,callerViewContainerRef.injector);