首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我想根据Angular 2中的不同端点数据显示不同的组件

我想根据Angular 2中的不同端点数据显示不同的组件
EN

Stack Overflow用户
提问于 2016-06-10 00:22:46
回答 1查看 363关注 0票数 1

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

例如

代码语言:javascript
运行
复制
{data: {type: 1, textToDisplay: 'I want beans'} }

应将组件%1注入主应用程序模板。

如果数据是

代码语言:javascript
运行
复制
{data: {type: 2, textToDisplay: 'I want cheese', numberToDisplay: '101' } }

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

我真的不想通过将元素附加到主应用程序模板中来使用糟糕的做法,我也不想编写一个带有[if]指令的大型模板,因为我们可能有许多,5-8个不同的组件要呈现,这会使模板变得臃肿。

什么是合适的方式?

EN

回答 1

Stack Overflow用户

发布于 2016-06-10 00:44:46

正如@Günter提到的,你可以使用DynamicComponentLoader

代码语言:javascript
运行
复制
@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

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

代码语言:javascript
运行
复制
this.cmp.instance.test = "the test";

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37731437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档