如何使用ngModel双向绑定将一个对象的某些属性绑定到另一个对象?
How to use ngModel two-way binding to bind some properties of one object to another object?
是否可以在 Angular 中使用双向绑定将一个对象的某些属性绑定到另一个对象?一个例子是这样的:
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>
非常感谢!
不,这是不可能的,因为 ngModel 指令的值将被设置为 select 元素的 selected 选项(在本例中)。所以这必须是要绑定到的单个 属性。
但是,如果您想将 selected 选项的值分配给多个属性,您可以使用 ngModelChange eventEmitter 来填充值:
<select [ngModel]="object1.property2" (ngModelChange)="object1.property2 = $event; object1.property3 = $event; object1.property4 = $event"> ... </select>
是否可以在 Angular 中使用双向绑定将一个对象的某些属性绑定到另一个对象?一个例子是这样的:
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>
非常感谢!
不,这是不可能的,因为 ngModel 指令的值将被设置为 select 元素的 selected 选项(在本例中)。所以这必须是要绑定到的单个 属性。
但是,如果您想将 selected 选项的值分配给多个属性,您可以使用 ngModelChange eventEmitter 来填充值:
<select [ngModel]="object1.property2" (ngModelChange)="object1.property2 = $event; object1.property3 = $event; object1.property4 = $event"> ... </select>