Angular - ngValue 没有绑定

Angular - ngValue is not binding

ngValue 不会绑定值,除非您保留同一列表的引用。正确吗?

这行不通:

this.myForm.get('user').patchValue(this.currentUser);

这会起作用:

const findIndex = this.user.findIndex(
  (item) => item.id == this.currentUser.id
);
this.myForm.get('user').patchValue(this.user[findIndex]);

另外,我又来了一个属性compareWith也可以用来绑定

如果我将它与 compareWith 一起使用,这将起作用。

this.myForm.get('user').patchValue(this.currentUser);

游乐场Link:https://stackblitz.com/edit/angular-ivy-a4zbhn?file=src%2Fapp%2Fapp.component.ts

您应该使用 [compareWith] 输入 属性 绑定到 <select> 元素,以便 Angular 可以通过您定义的比较将值绑定到 <select>逻辑。

.component.html

<select formControlName="user" [compareWith]="compare">
  <option *ngFor="let us of user" [ngValue]="us">{{ us.name }}</option>
</select>

.component.ts

compare(val1, val2) {
  return val1.id === val2.id;
}

Sample Solution on StackBlitz


更新备注:

Angular - SelectControlValueAccessor (Customizing option selection section)所写,

Angular uses object identity to select option.

没有[compareWith],默认情况下Angular将使用对象引用到select选项。

因此,只要您为对象提供精确引用,您对第一种方法的推断是正确且可行的,因为对象存在于[ngValue].

const findIndex = this.user.findIndex(
    (item) => item.id == this.currentUser.id
);

this.myForm.get('user').patchValue(this.user[findIndex]);

参考资料

Customizing option selection