我对Angular相当新,所以如果我在这里遇到一些菜鸟错误,请耐心等待:) 我基于一些需要填写的属性(this.properties)动态添加输入,我想将每个动态输入绑定到某个对象(this.selectedProperties = {}),这样我最终得到这样的东西
this.properties = [new MyData { name = "theName", examples = "theExamples" },
new MyData { name = "anotherName", examples = "moreExamples" }];
this.selectedProperties = { "theName": "valueFromBinding", "anotherName": "anotherValueFromBinding" }
这是我迄今为止的精简版。除了ngModel之外,其他所有工作都可以设置所选的值。
<div *ngFor="let property of this.properties">
<label>{{property.name}}</label>
<input type="text" placeholder="{{property.examples}}"
[ngModel]="this.selectedProperties[property.name]"
name="{{property.name}}Input">
</div>
谢谢!
答案 0 :(得分:0)
试试这样:
<强> component.html 强>
<div *ngFor="let property of properties">
<label>{{property.name}}</label>
<input type="text" placeholder="{{property.examples}}" [ngModel]="selectedProperties[property.name]" name="{{property.name}}Input">
</div>
<强> component.ts 强>
export class AppComponent {
properties = [
new MyData { name: "theName", examples: "theExamples" },
new MyData { name: "anotherName", examples: "moreExamples" }
];
selectedProperties = {
"theName": "valueFromBinding",
"anotherName": "anotherValueFromBinding"
};
}
答案 1 :(得分:0)
原来我需要双向绑定,以便当用户在UI中更改它时,selectedProperties [property.name]会更新