【问题标题】:Insert different Angular2 components programmatically以编程方式插入不同的 Angular2 组件
【发布时间】:2016-05-01 16:46:46
【问题描述】:

我想以编程方式从 JSON 文件中生成由多个不同组件组成的报告,例如:

{
    components: [UserStatsComponent, ActivityChartComponent, NetworkGraphComponent]
}

我发现了这个:Angular2: Creating child components programmatically 但我的用例不同,因为我需要表示不同类型的组件,所以我不能在模板中使用 ngFor,因为不是每个组件都有相同的指令。

我是 Angular2 的新手,所以我真的不知道如何解决这个问题:首先我想到了组件继承,但看起来 angular2 注释在扩展组件的类时没有被继承。也不知道如何使用组合来解决这个问题。

听说过有关内容标签的一些信息,但不知道它是否与此用例相关。

tldr;如何从数组中动态插入不同的组件?

【问题讨论】:

  • su pregunta no es clara... 它会造成混乱。你能把它做得更好吗?
  • tldr;如何从数组中动态插入不同的组件?
  • 是否要经过json对象循环,并且要制作遇到的动态组件?
  • 如果你说你不知道你将插入什么子组件,这意味着你说你不知道如何为每个组件定义 @component 装饰器。所以,我认为它看起来并不直接和简单的答案。但希望你可以看看 angular2 的DynamicComponentLoader。但希望其他人现在或以后能够回答。

标签: inheritance dynamic components angular composition


【解决方案1】:

要动态插入组件,请使用DynamicComponentLoader

@Component({
  selector: 'child-component',
  template: 'Child'
})
class ChildComponent {
}
@Component({
  selector: 'my-app',
  template: 'Parent (<child id="child"></child>)'
})
class MyApp {
  constructor(dcl: DynamicComponentLoader, injector: Injector) {
    dcl.loadAsRoot(ChildComponent, '#child', injector);
  }
}

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2015-08-30
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2013-05-15
    相关资源
    最近更新 更多