Search code examples
angularngmodel

How to use ngModel two-way binding to bind some properties of one object to another object?


Is is possible to bind some properties of one object to another object using two way binding in Angular? One example is like:

JS

object_1 {
    property1:string,
    property2:string,
    property3:string,
    property4:string
}

object_2 {
    property1:string,
    property2:string,
    property3:string
}

objects_1: object_1[];
objects_2: object_2[];

HTML

<ul>
  <li *ngFor="let object1 of objects_1">
    <input type="text" [(ngModel)]="object1.property1"> 
    <select [(ngModel)]="object1.property2+object1.property3+object1.property4">
        <option *ngFor="let object2 of objects_2" [ngValue]="object2">
        </option>
    </select>
  </li>
</ul>

Thank you very much!


Solution

  • no this is not possible since the value of the ngModel directive will be set as the selected option of the select element (in this case). So this must be a single property to bind to.

    However if you want to assign the value of the selected option to multiple properties, you could use the ngModelChange eventEmitter to populate the values:

    <select [ngModel]="object1.property2" (ngModelChange)="object1.property2 = $event; object1.property3 = $event; object1.property4 = $event"> ... </select>