gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:11:34 24 4
gpt4 key购买 nike

在 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 组件列表,如果所选值不再出现在各自可能的选项列表中,则可以更新这些组件。我的问题是,其中每一个都通过双向绑定(bind)链接到对象 selectedItems 的条目,但是在分配 x['value'] = ... 时新值不会在 selectedItems 中传播。直接更改上面代码片段中的字典并不容易,因为我没有相关的 key 。除了 x['value'] = ... 之外,还有其他方法可以保留此处的双重绑定(bind)吗?

这是我所指出的行为的示例:

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

最佳答案

这是因为您提供对象作为选项的值。

如果您这样做,您必须为您的选择提供自定义比较 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;
}

关于angular - Mat-select 更改值不会通过双向绑定(bind)传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53498966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com