我有一个mat-select绑定到一个对象Id,当我更改选项时,我打开一个确认警报,我希望所选的选项只在我说“确定”时更改,如果我说“确定”,如果我取消它,我尝试选择的选项保持选中,不是在值上,而是在显示上。
我尝试将ngModel设置为相同的,但这没有任何作用,因为我的ngModel值没有被更改,只有选中的选项。
<mat-select title="Repartidor" placeholder="Repartidor" [ngModel]="order._ShippingProviderId" (selectionChange)="shippingProviderChange(order, $event)">
<mat-option *ngFor="let driverStatus of driverStatuses" [value]="driverStatus._ShippingProvider._Id">
{{driverStatus._ShippingProvider._Name}}
</mat-option>
</mat-select>shippingProviderChange(order: IOrder, event: MatSelectChange){
if(confirm("¿Quieres asignar este repartidor?")) {
// change option
console.log(order._ShippingProviderId);
order._ShippingProviderId = event.value;
console.log(order._ShippingProviderId);
}
else{
// keep the same option selected
}
}mat-select保留我没有确认的选项,而不是保留最后一个选项。将选项重置为none不是一个选项,因为我的选项被绑定到对象。
更新#1:
我尝试过这样做,它确实将选定的值更改为上一个值,但它没有将所选的选项设置为它的原始状态。
else{
var same = order._ShippingProviderId;
order._ShippingProviderId = undefined;
order._ShippingProviderId = same;
}发布于 2020-09-23 16:27:21
我们发现处理这些问题的最佳方法是设置一个单独的变量来跟踪实际值,并根据确认结果有条件地设置它。mat-select-trigger移除它的外观,来回切换。
如果有任何事情取决于基于此的选择、更改和运行代码的值,则不必担心。它可以根据实际跟踪值的变量的变化(在本例中为selectedValue )运行,也可以在onSelectionChanged方法内触发。
html:
<mat-select
[(ngModel)]="userSelectedValue"
(selectionChange)="onProgramChanged($event.value)">
<mat-select-trigger>{{selectedValue}}</mat-select-trigger>
<mat-option *ngFor="let option of myOptions> {{option}}<mat-option>
</mat-select>ts:
userSelectedValue; // ngmodel value
selectedValue; // actual value you use
onSelectionChanged() {
this.openConfirmationDialog((confirmed) => { //prompt user for confirmation
if(confirmed === 'confirm') {
this.selectedValue = this.userSelectedValue;
this.dologic()
} else {
this.userSelectedValue= this.previousUserSelectedValue;
}
}https://stackoverflow.com/questions/56743028
复制相似问题