Mat-select 更改值不会通过双向绑定传播
Mat-select changing value does not propagate through 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'] = ...
之外,还有其他方法可以保留此处的双重绑定吗?
这是我所指出的行为示例:
那是因为您提供对象作为选项的值。
如果这样做,您必须提供与 select、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;
}
在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'] = ...
之外,还有其他方法可以保留此处的双重绑定吗?
这是我所指出的行为示例:
那是因为您提供对象作为选项的值。
如果这样做,您必须提供与 select、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;
}