angular - Angular2 - bind ngModel to a reference of a property -
i have long list of user inputs, , store these in object instead of spelling them out in html. want bind these values object stores user/customer's data. preferably using ngmodel due simplicity , functionality.
anyone knows how can achieve this?
example below (not working).
@component({ template: ` <div> <h2>ngmodel example</h2> <div *ngfor="let input of inputlist"> {{ input.label }} <input type="text" [(ngmodel)]="input.bindto"> </div> </div> <p>this not working: {{customerinfo.name}}, {{customerinfo.email}}</p> `, directives: [...] }) export class appcomponent { inputlist = [ { label: "enter name", bindto: this.customerinfo.name // tried 'customerinfo.name' }, { label: "enter email", bindto: this.customerinfo.email } ] customerinfo = { name: 'test', email: '' } }
that's not supported. ngmodel
can bind property of component. don't see way refer component property string literal template without helper methods:
this might work you:
<div *ngfor="#input of inputlist"> {{ input.label }} <input type="text" [ngmodel]="getprop(input.bindto)" (ngmodelchange)="setprop(input.bindto, $event)"> </div>
inputlist = [ { label: "enter name", bindto: "name" }, { label: "enter email", bindto: "email" } ]; getprop(prop) { return this[prop]; } setprop(prop, value) { this[prop] = value; }
<div *ngfor="#input of inputlist; #i = index"> {{ input.label }} <input type="text" [(ngmodel)]="inputlist[i]"> </div>
hint => rc.0 #
should replaced let