I have a long list of user inputs, and would like to store these in an object instead of spelling them out in HTML. I want to bind these values to another object that stores the user/customer's data. Preferably using ngModel due to its simplicity and functionality.
Anyone knows how I 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 is not working: {{customerInfo.name}}, {{customerInfo.email}}</p>
`,
directives: [...]
})
export class AppComponent {
inputList = [
{
label: "Enter your name",
bindTo: this.customerInfo.name // also tried 'customerInfo.name'
},
{
label: "Enter your email",
bindTo: this.customerInfo.email
}
]
customerInfo = {
name: 'test',
email: ''
}
}
That's not supported. ngModel
can only bind to a property of the component. I also don't see a way to refer to a component property by a string literal from the template without helper methods:
This might work for you:
<div *ngFor="#input of inputList">
{{ input.label }}
<input type="text"
[ngModel]="getProp(input.bindTo)"
(ngModelChange)="setProp(input.bindTo, $event)">
</div>
inputList = [
{
label: "Enter your name",
bindTo: "name"
},
{
label: "Enter your 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 for => RC.0 #
should be replaced by let
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With