问题描述
注意:我发现了几个类似的问题,但没有一个问题能真正回答我的(通用)问题
NOTE: I found several similar questions but none really answered my (generic) question
我有这个
component.ts
first: string;
second: string;
third: string;
fields = ["first", "second", "third"];
我希望能够在 component.html 中生成一个复杂的组件(而无需导入自定义指令),该组件包括:
I want to be able to generate in component.html a complex component (without importing a custom-defined directive) which includes:
-
必需:基于字段的ngModel绑定[i]
Required: ngModel binding based on fields[i]
(例如,i = 0,fields [i] ="first",ngModel = first )
(e.g. i = 0, fields[i] = "first", ngModel = first)
理想:使用字段[i]作为字符串分配给任何DOM元素属性(例如
Desiderable: use fields[i] as strings to assign to any DOM element property (e.g.
循环看起来像这样:
<div *ngFor="let field of fields">
<label for="???>
[(ngModel)]="???"
</div>
关于第二点,它与id和div的内容一起使用.
As for the 2nd point, it works with id and as content of the div.
但是...
- 对于ngModel:[[ngModel)] ="field"导致异常(无法分配给引用或变量!)
-
(例如,将字符串分配给)
- in the case of ngModel: [(ngModel)] = "field" leads to an exception (Cannot assign to a reference or variable!)
in the case of assigning a string to (for example)
<label for="{{field}}">,
我也有一个例外(因为它不是已知的本机属性,所以无法绑定到"for"("i> )
推荐答案
> = RC.6
<label for="{{field}}">
<label [for]="field">
< = RC.5
<label attr.for="{{field}}">
<label [attr.for]="field">
<label [htmlFor]="field">
更新
<div *ngFor="let field of fields; let i=index; trackBy:trackByIndex">
<label htmlFor="field">
<input [(ngModel)]="fields[i]">
</div>
并将其添加到组件中
trackByIndex(index: number, obj: any): any {
return index;
}
这篇关于如何在Angular 2中的ngFor中设置绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!