首页 > 解决方案 > Mat-Select 确认选择

问题描述

我有一个绑定到对象 ID 的 mat-select,当我更改选项时,我打开一个确认警报,我希望所选选项只有在我说 OK 时才会更改,如果我取消它,我尝试选择的选项保持选中状态,而不是在价值上,但在展示上。

我尝试将 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 保留我没有确认选择的选项,而不是保留最后一个。将选项重置为无不是一个选项,因为我的选项绑定到对象。

更新#1:

我试过了,它确实将选定的值更改为前一个值,但它没有将选定的选项设置为原始状态。

else{ 
    var same = order._ShippingProviderId; 
    order._ShippingProviderId = undefined;
    order._ShippingProviderId = same;
}

标签: javascriptangulartypescript

解决方案


我们发现处理这些问题的最佳方法是设置一个单独的变量来跟踪实际值,并根据确认结果有条件地设置它。mat-select-trigger消除了它来回切换的外观。

如果有什么依赖于 select 的值,并以此为基础更改和运行代码,则不必担心。它可以基于实际跟踪值的变量的变化运行,在这种情况下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;
       }
 }

推荐阅读