【问题标题】:I want to display different components based on different endpoint data in Angular 2我想在 Angular 2 中根据不同的端点数据显示不同的组件
【发布时间】:2016-10-10 10:18:57
【问题描述】:

我正在做一个项目,我需要根据我的端点响应显示不同的模板/组件。

例如

{data: {type: 1, textToDisplay: 'I want beans'} }

应该将组件 1 注入到主应用模板中。

如果数据是

{data: {type: 2, textToDisplay: 'I want cheese', numberToDisplay: '101' } }

应该将组件 2 注入主应用程序模板,当然组件 2 会与组件 1 不同,因为有额外的属性。

我真的不想通过将元素附加到主应用程序模板来使用不好的做法,我也不想使用 [if] 指令编写一个庞大的模板,因为我们可以有许多 5-8 个不同的组件来渲染和它会使模板膨胀。

什么是合适的方式?

【问题讨论】:

标签: angular rxjs angular2-template angular2-directives


【解决方案1】:

正如@Günter 所说,您可以使用DynamicComponentLoader

@Component({
  selector: 'my-app',
  template: `<button (click)="addCmp()" #theBody>add</button>
  `,
  directives: [BaseDynamicComponent]
})
export class AppComponent {
  @ViewChild('theBody', {read: ViewContainerRef}) theBody;
  cmp:ComponentRef;

  constructor(injector: Injector,private resolver: ComponentResolver) {}

  addCmp(data){
    console.log('adding');
    this.resolver.resolveComponent(BaseDynamicComponent).then((factory:ComponentFactory<any>) => {
      this.cmp = this.theBody.createComponent(factory);
      //and you can set your BaseDynamicComponent's 'extra' properties here
      this.cmp.instance.numberToDisplay = data.numberToDisplay;
    });
  }
  }

这将在#theBody 元素下添加 BaseDynamicComponent。

这是一个 plunkr 示例:

Plunker

如果您单击添加按钮,它将添加一个新组件,其测试字段分配给“测试”

this.cmp.instance.test = "the test";

或者您可以像@Günter's answer(https://stackoverflow.com/a/36325468/5706293) 中预定义组件,然后相应地附加它们

【讨论】:

  • DynamicComponentLoader 已弃用,请改用ViewContainerRef.createComponent()。请参阅我上面的链接。
  • 我看到你已经更新了代码。如果你不使用它就不需要注入DynamicComponentLoader ;-)
  • @GünterZöchbauer 先生,我马上更新它,这是一个旧模板:D
  • 非常感谢,我会在下周查看并回复您,但谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多