我正在处理一个项目,其中我需要根据我的端点响应显示不同的模板/组件。
例如
{data: {type: 1, textToDisplay: 'I want beans'} }
应将组件%1注入主应用程序模板。
如果数据是
{data: {type: 2, textToDisplay: 'I want cheese', numberToDisplay: '101' } }
应该将组件2注入到主应用程序模板中,当然组件2将不同于组件1,因为有额外的属性。
我真的不想通过将元素附加到主应用程序模板中来使用糟糕的做法,我也不想编写一个带有[if]
指令的大型模板,因为我们可能有许多,5-8个不同的组件要呈现,这会使模板变得臃肿。
什么是合适的方式?
发布于 2016-06-10 00:44:46
正如@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
如果您单击add按钮,它将添加一个新组件,并将其测试字段分配给"the test“
this.cmp.instance.test = "the test";
或者,您可以像@Günter's answer(https://stackoverflow.com/a/36325468/5706293)中那样预定义组件,然后相应地附加它们
https://stackoverflow.com/questions/37731437
复制相似问题