Lea*_*ess 2 angular-material angular 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>
Run Code Online (Sandbox Code Playgroud)
在 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"];
}
});
});
Run Code Online (Sandbox Code Playgroud)
此代码描述了一个组件列表mat-select,如果所选值不再位于其各自可能的选项列表中,则可以更新该列表。我的问题是,其中每一个都通过双向绑定链接到对象的条目selectedItems,但是在分配x['value'] = ...新值时不会在selectedItems. 直接更改上面代码片段中的字典并不容易,因为我没有相关的密钥。除此之外还有其他方法x['value'] = ...可以保留这里的双重绑定吗?
这是我指出的行为的示例:
小智 7
这是因为您提供对象作为选项的值。
如果这样做,您必须为您的选择提供自定义比较,如文档中所述
<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>
Run Code Online (Sandbox Code Playgroud)
customCompare(o1, o2) {
return o1.id === o2.id;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7149 次 |
| 最近记录: |