Mat-select更改值不会通过双向绑定传播

时间:2018-11-27 11:46:32

标签: angular angular-material two-way-binding

在html方面,我有:

    <mat-select #footageSelects [(ngModel)]="selectedItems[element.id]">
      <ng-container *ngFor='let opt of element.items; index as index'>
        <mat-option [value]="opt">{{opt.label}}
        </mat-option>
      </ng-container>
    </mat-select>

在ts方面,我有:

@ViewChildren('footageSelects') _footageSelects: QueryList<ElementRef>;
....

this._footageSelects.toArray().map(x => {
    setTimeout(() => {
        //sets a value in the select if not defined or no more in the options
        if (!x['options'].some(y => y['value'] === x['value'])) {
            x['value'] = x["options"]["first"]["value"];
        }
    });
});

此代码描述了mat-select个组件的列表,如果所选值不再位于它们各自可能的选项列表中,则可以对其进行更新。我的问题是,每个对象都通过双向绑定链接到对象selectedItems的条目,但是在分配x['value'] = ...时,新值不会在selectedItems中传播。不容易直接在上面的代码片段中更改字典,因为我没有相关的键。除了x['value'] = ...以外,还有没有其他方法可以在此处保留双重绑定?

这是我要指出的行为的一个示例:

https://stackblitz.com/edit/angular-tdsywh

1 个答案:

答案 0 :(得分:1)

那是因为您将对象提供为选项的值。

如果这样做,则必须提供与所选as explained in the documentation

的自定义比较
<mat-select #footageSelects [(ngModel)]="selectedItems[element.id]" [compareWith]="customCompare">
  <ng-container *ngFor='let opt of element.items; index as index'>
    <mat-option [value]="opt">{{opt.label}}
    </mat-option>
  </ng-container>
</mat-select>
customCompare(o1, o2) {
  return o1.id === o2.id;
}
相关问题