javascript - 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;
}
解决方案
我们发现处理这些问题的最佳方法是设置一个单独的变量来跟踪实际值,并根据确认结果有条件地设置它。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;
}
}
推荐阅读
- arrays - 用于存储大数据的动态数据结构数组
- excel - 从excel中删除列中已终止值的行
- mongodb - Mongoose - 选择具有对象数组作为搜索参数的文档
- node.js - 如何在nodejs黄瓜硒中使用for循环创建动态xpath
- ansible - 这个变量是可见的吗?
- java - 在 Java 的 3 个文件中找到常用词的有效方法是什么?
- c# - 使用 log4net 记录传入请求的 IP 地址
- node.js - NodeJS 和 TLS,获取客户端证书
- python - 如何读取逗号旁边有双引号的csv文件
- java - Netbeans 9:有没有办法改变新生成方法的位置?