Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - bind ngModel to a reference of a property

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: ''
  }
}
like image 457
Daniel Mattsson Avatar asked Jun 02 '16 06:06

Daniel Mattsson


1 Answers

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

like image 196
Günter Zöchbauer Avatar answered Oct 16 '22 14:10

Günter Zöchbauer