动态添加组件Angular 5

时间:2018-05-29 06:26:32

标签: angular typescript

我遇到了问题,我不确定是什么问题。

所以我想使用查询参数动态地将组件添加到另一个组件。

所以我动态添加了组件但是当我使用具有完全相同名称的查询字符串时它不起作用

所以路线设置如下

{
    path: 'tool-view/:tool',
    component: ToolViewerComponent
}

然后在app.module中我正在添加我试图动态添加到entryComponents的组件,就像这样......

entryComponents: [
    CoolToolComponent
]

然后在我的toolViewerComponent中我有了这个

import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

// Tool Components
import { CoolToolComponent } from '../tools/cool-tool/cool-tool.component';

@Component({
  selector: 'app-tool-viewer',
  templateUrl: './tool-viewer.component.html',
  styleUrls: ['./tool-viewer.component.scss']
})
export class ToolViewerComponent implements OnInit {

  @ViewChild('entry', { read: ViewContainerRef }) entry: ViewContainerRef;

  constructor(
    private _resolver: ComponentFactoryResolver,
    public activatedRoute: ActivatedRoute
  ) { }

  ngOnInit() {
    // Resolvers
    const coolFactory = this._resolver.resolveComponentFactory(CoolToolComponent);
    const toolComponent = this.entry.createComponent(coolFactory);
  }
}

好的,所以这个工作,当我尝试这个时,组件被添加到页面上没问题...

@ViewChild('entry', { read: ViewContainerRef }) entry: ViewContainerRef;

constructor(
  private _resolver: ComponentFactoryResolver,
  public activatedRoute: ActivatedRoute
) { }

ngOnInit() {
  this.activatedRoute.params.subscribe(params => {
    this.createComponent(params.tool);
  });
}

createComponent(tool) {
  const toolFactory = this._resolver.resolveComponentFactory(tool);
  const toolComponent = this.entry.createComponent(toolFactory);
}

但这不起作用,我收到错误

No component factory found for CoolToolComponent. Did you add it to @NgModule.entryComponents?

我不完全确定这里会发生什么,但我想我可能会在createComponent(tool)工具以字符串"CoolToolComponent"而不是CoolToolComponent的形式出现这一事实} ??

但我不确定。

我能想到的另一种方法就是使用一堆if语句。

if(params.tool = 'CoolToolComponent') {
    const hba1cFactory = this._resolver.resolveComponentFactory(Hba1cTracker);
    const toolComponent = this.entry.createComponent(hba1cFactory);
} etc..

我想避免这样做。

任何帮助将不胜感激!

由于

1 个答案:

答案 0 :(得分:1)

您可以创建一个包含动态组件集的数组,其中路由参数是相应组件的关键。像这样:

import { Component } from '@angular/core';
...
import { ToolComponent} from './tool.component';

@Component({...})
export class ToolViewerComponent  {
  ...

  tools: Component[] = new Array();

  constructor() {
    // add more tools here...
    this.tools['tool'] = ToolComponent;
  }

  ngOnInit() {
  this.activatedRoute.params.subscribe(params => {
    let toolName = param.tool;
    this.createComponent(this.tools[toolName]);
  });
}

createComponent(tool: Component) {
  const toolFactory = this._resolver.resolveComponentFactory(tool);
  const toolComponent = this.entry.createComponent(toolFactory);
}

}