使用ngModel绑定动态生成的输入

时间:2017-11-29 17:04:56

标签: javascript angular angular2-ngmodel

我对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>

谢谢!

2 个答案:

答案 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]会更新