有两件事我想要实现。两者都需要巧妙地使用组件。
首先,一个关于组件绑定的一般问题:在我看到的每一篇文章中,都会在模板中使用指令标记来绑定组件。然而,由于我的两个问题,我不能事先把我的指令放在模板中-相反,我需要动态地这样做。
博士,我如何动态地绑定组件,而不设置正确数量的绑定和它们各自的类型?
发布于 2017-01-13 21:31:59
当组件信息来自服务器时,您可以做一件事:
您仍然必须将所有组件放在父模板中,但只显示服务器返回的内容:
<div *ngFor="let dynamic of fromServer" [ngSwitch]="dynamic .id">
<thing-a *ngSwitchCase="'thinga'" [data]="dynamic"></thing-a>
<thing-b *ngSwitchCase="'thingb'" [data]="dynamic"></thing-b>
<thing-c *ngSwitchCase="'thingc'" [data]="dynamic"></thing-c>
<thing-d *ngSwitchCase="'thingd'" [data]="dynamic"></thing-d>
<thing-e *ngSwitchCase="'thinge'" [data]="dynamic"></thing-e>
<thing-f *ngSwitchCase="'thingf'" [data]="dynamic"></thing-f>
</div>因此,如果服务器返回:
[
{ id : "thinga" }
{ id : "thingd" }
{ id : "thingf" }
]然后只有这3将被显示。
您还可以根据服务器返回数据的顺序对组件进行动态排序。
编辑:
如果服务器返回3次thinga,则将显示3次。
编辑2:示例:
[
{ id : "thinga", title: "Yes"}
{ id : "thinga", title: "No" }
{ id : "thinga", title: "Maybe" }
]每个thinga组件都将获得自己的数据。
https://stackoverflow.com/questions/41643342
复制相似问题