html - 在 Angular 中,不会为 angular mat-option 调用 onSelectionChange

标签 html angular angular-material

我有一个包含输入的 mat-form-field 和一个包含 mat-option 的 mat-autocomplete。输入有 (blur) 事件,而 mat-option 有 (onSelectionChange) 事件。

我遇到的问题是,当我选择一个项目时,会在 mat-option 的 onSelectionChange 事件之前调用模糊。如果下拉列表中不存在该值,则模糊事件的方法会清空输入。如果我删除输入的 (blur) 事件,则 (onSelectionChange) 被调用。我需要在(模糊)事件之前调用它。

经过一些研究,我发现我可以在 (blur) 的函数内使用 .setTimeOut ,它允许在 (onSelectionChange) 的函数之后调用它的主体,但是,通过此修复,远离输入将延迟清空输入如果它有一个错误的值。

这是我拥有的 html 代码:

<mat-form-field [style.width.%]="fieldWidthPercentage">
    <input matInput #tagsInput (blur)="checkIfMatch()">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let item of filteredAutoCompleteItems | async" 
      (onSelectionChange)="selected(item)" [value]="item">
      {{ item.name }}
    </mat-option>
    </mat-autocomplete>
</mat-form-field>

这是(模糊)事件的函数:
checkIfMatch() {
    setTimeout(() => {
    // . . .
    }, 1000);
  }
}

最佳答案

您应该在 (optionSelected) 上使用 <mat-autocomplete>

<input matInput #tagsInput (blur)="checkIfMatch()">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event.option.value)">
  <mat-option *ngFor="let item of filteredAutoCompleteItems | async" 
    [value]="item">
    {{ item.name }}
  </mat-option>
</mat-autocomplete>

文档:https://material.angular.io/components/autocomplete/api#MatAutocompleteSelectedEvent

示例:Mat-autocomplete - How to access selected option?

关于html - 在 Angular 中,不会为 angular mat-option 调用 onSelectionChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52936740/

相关文章:

html - CSS SVG 文本阴影位于文本之上

Angular 模拟多个 HTTP 调用

ajax - XMLRPC 请求中的访问控制允许来源问题

html contentEditable document.execCommand 更改选定的不透明度

javascript - 使用 javascript 更改 nav/div 的内容

Angular 是否有必要取消订阅 this.activatedRoute 订阅

Angular2 + ngrx/store 用于处理失败的 HTTP 请求

angular - 如何在 Angular Material 表中对单个表使用 2 分页?

angular - 无法读取未定义的属性 - cdkDropListData 拖放 Angular Material

html - 更改垫进度条 "aria-valuemax"