【发布时间】:2016-07-27 07:57:10
【问题描述】:
我想要实现的是一个通用组件,它绑定到一个任意对象数组,当每行的视图也由使用它的主组件任意定义时,它允许动态添加和删除行。
请注意,MasterComponent 是一个任意组件,可以为不同的页面实现,旨在自包含,而不是由任何元数据或外部源定义。
到目前为止,我拥有以下组件:
RepeaterComponent 模板:
<input type="button" value="Add" (click)="addRow()">
<div class="repeater" *ngFor="let row of repeaterArray">
<div class="repeaterRow">
<input type="button" value="Remove" (click)="removeRow(row.rowId)">
<ng-content select="row"></ng-content>
</div>
</div>
MasterComponent 模板:
<repeater [repeaterArray]="repeaterObj">
<row>
<field-textbox [data]="row.name" [label]="'Name'"></field-textbox>
<field-textbox [data]="row.description" [label]="'Description'"></field-textbox>
</row>
</repeater>
<field-textbox> 组件是我用来封装简单输入的自定义组件,其中包含一些我需要使用的额外数据。
MasterComponent 包含一个对象,对于该实例,该对象如下所示:
repeaterObj = [
{
"rowId": 1,
"name": "First brand",
"description": "First description"
},
{
"rowId": 2,
"name": "Second brand",
"description": "Second description"
},
{
"rowId": 3,
"name": "Third brand",
"description": "Third description"
}
];
这种方法有两个我似乎找不到解决方案的问题。
-
ng-content选择器对于所有行都是相同的,当ngFor复制模板时,渲染后我只剩下一个ng-content嵌入点。 - 在
<field-textbox>嵌入指令中的ngFor声明中没有对row变量的引用,因此我无法正确绑定数据。
有没有更好的方法来实现RepeaterComponent,这样我就可以用最少的精力来创建更多具有不同任意结构和不同模板的新MasterComponents?
【问题讨论】:
标签: angular angular2-ngcontent