从选择器

时间:2018-05-08 02:41:06

标签: angular typescript

我有一个应用程序,其中包含很多组件,这些组件是RxJS运算符的可视化,例如rx-maprx-filterrx-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

虽然这确实有效,但实际上并没有为每个单独的可视化创建路线做任何工作。

有没有办法从选择器创建组件或以其他方式在应用程序中编译模板字符串并注入?

1 个答案:

答案 0 :(得分:0)

您可以在NgModule中定义所有Rx *组件,并使用ngContainerOutlet动态加载它们。请参阅文档here

在最简单的情况下:

<ng-container *ngComponentOutlet="RxMapComponent"></ng-container>

您还可以将ngComponentOutletNgModuleFactory与ngComponentOutlet一起使用,以指定一个可选的模块工厂,使您能够动态加载另一个模块,然后从该模块加载组件。

<ng-container *ngComponentOutlet="RxMapComponent;
                                  ngModuleFactory: myRxModule;"></ng-container> 

要对此进行参数化,您可以将上面的代码包装到通用的WidgetComponent中:

<widget componentName="RxMapComponent"></widget>

由于组件名称是一个字符串,您仍然需要维护从组件名称到组件类型的映射(Type&lt; any&gt;):

case 'RxMapComponent': return RxMapComponent

这样做的主要好处是您无需设置单独的路线。