[英]Compile Angular component from selector
我有一个应用程序,其中包含很多组件,这些组件是RxJS运算符的可视化对象,例如rx-map
, rx-filter
, rx-reduce
等。可视化文件本身可以很好地工作。 我现在想做的是允许用户选择他们想通过路由器看到的可视化效果。 我可以通过为每个单独的组件创建一条路线来做到这一点,但是有很多路线,因此会有很多手动路线。
我试图让Angular使用ComponentFactoryResolver
来做到这一点。 我可以这样工作:
@Component({
selector: 'rx-visualizations-app',
template: '<ng-template #container></ng-template>',
})
export class RxVisualizationsAppComponent implements OnInit, OnDestroy {
@ViewChild('container', { read: ViewContainerRef })
container: ViewContainerRef;
private componentRef: ComponentRef<{}>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit() {
const factory = this.componentFactoryResolver.resolveComponentFactory(
getComponentFromRoute(),
);
this.componentRef = this.container.createComponent(factory);
}
}
这可以正常工作,并且可以正确显示组件。 问题是我必须拥有到组件名称的组件路由的完整列表,并且还必须导入其中的每一个,例如:
switch (route) {
case 'map': return RxMapComponent
尽管这确实可行,但它并不仅仅是为每个单独的可视化创建路线而已,实际上并没有减少任何工作。
有没有一种方法可以通过选择器创建组件或以其他方式在应用程序中编译模板字符串并将其注入?
您可以在NgModule中定义所有Rx *组件,并使用ngContainerOutlet
动态加载它们。 在这里查看文档。
在最简单的情况下:
<ng-container *ngComponentOutlet="RxMapComponent"></ng-container>
您还可以将ngComponentOutletNgModuleFactory
与ngComponentOutlet一起使用,以指定一个可选的模块工厂,该工厂将使您能够动态加载另一个模块,然后从该模块加载组件。
<ng-container *ngComponentOutlet="RxMapComponent;
ngModuleFactory: myRxModule;"></ng-container>
为了对此进行参数化,您可以将上面的代码包装到一个通用的WidgetComponent中:
<widget componentName="RxMapComponent"></widget>
由于组件名称是字符串,因此您仍然需要维护从组件名称到组件类型(Type <any>)的映射:
case 'RxMapComponent': return RxMapComponent
这样做的主要好处是您不必设置单独的路线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.