javascript - Mat select - 获取selectionChange的旧值

标签 javascript angular

我有一个项目,其中有一个包含 mat-select 选择器的表单。每当用户更改输入时,我都会向用户显示一个对话框来确认此操作。现在:

selectionChange() 会在值发生更改时发出通知,并将新值作为 $event 传递。

有没有办法在用户取消对话框时返回旧值?

我不想做一些肮脏的事情,比如将当前值保存在单独的成员变量中。

模板:

<mat-select [(ngModel)]="selectedTextCountingType" 
            (selectionChange)="select($event)">
  <mat-option *ngFor="let option of countingTypeOptions" 
              [value]="option.value">
    {{option.text | translate}}
  </mat-option>
</mat-select>

TS:

select(option: MatSelectChange): void { 
    this.openConfirmDeletionDialog().pipe(
        filter((respose) => {
            // HERE IS WHERE I NEED IT.
            if(Boolean(reponse) === false) {
                this.selectedTextCountingType = oldValue;
            }
            return Boolean(reponse); 
        })
    )
}

最佳答案

实际上,有一个解决方法可以满足您的预期行为,因为当触发事件 selectionChange 时,您将模型绑定(bind)到该垫选择,您的元素已经更新,但是如果您打印出模型将是选择标签最后一次由 Angular 更新时形成的文字,在您的情况下,因为您是类型列表的 ngFor,您稍后可以通过文本、值或您可能喜欢的任何其他属性找到它。

<mat-select [(ngModel)]="selectedTextCountingType" 
            (selectionChange)="select($event, '{{selectedTextCountingType.value}}')">
  <mat-option *ngFor="let option of countingTypeOptions" 
              [value]="option.value">
    {{option.text | translate}}
  </mat-option>
</mat-select>

并且在您的组件中,您应该将值作为字符串

select(option: MatSelectChange, oldValue: string): void { 
    this.openConfirmDeletionDialog().pipe(
        filter((respose) => {
            if(Boolean(reponse) === false) {
                this.selectedTextCountingType = this.selectedTextCountingType.find(countingType => countingType.value === oldValue);
            }
            return Boolean(reponse); 
        })
    )
}

关于javascript - Mat select - 获取selectionChange的旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58522591/

相关文章:

javascript - Angular js 将更改的值推送到数组中

Javascript eval() 不适用于传递的字符串

javascript - 如何从具有特定 alt= 值的字符串中删除图像元素?

javascript - 出现404错误时如何获取post json?

javascript - Angular 2 - 我有 3 个 header 组件。如何最好地切换这两个标题?

javascript - 递归 Angular div模板

javascript - 一次切换 2 个类?

Angular Cli - 未找到 Dojo 模块

angular - 从一个 View 到另一个 View 访问模板引用变量

javascript - 使用 JavaScript 在 HTML 表格中添加行