【问题标题】:In Angular, onSelectionChange is not getting invoked for angular mat-option在 Angular 中,不会为 Angular mat-option 调用 onSelectionChange
【发布时间】:2019-03-26 23:09:42
【问题描述】:

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

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

经过一些研究,我发现我可以在 (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);
  }
}

【问题讨论】:

    标签: html angular angular-material


    【解决方案1】:

    您应该在&lt;mat-autocomplete&gt; 上使用(optionSelected)

    <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?

    【讨论】:

    • 这很好用,只是 checkIfMatch() 仍然在所选函数之前被调用。我需要一种仅在失去焦点时才调用模糊的方法,而不是在从下拉列表中选择选项时调用模糊
    【解决方案2】:

    我找到了我的问题的解决方案: 对于 blur 的调用,我添加了一个检查以查看事件的相关目标是否来自 mat-option,在这种情况下,不会调用 checkIfMatch 的代码:

    checkIfMatch(event) {
    
        if (event.relatedTarget && event.relatedTarget.id.indexOf('mat-option') > -1) {
          // In case of a direct selection, there is no need to check if it matches.
          event.preventDefault();
          return;
        }
    ...
    }
    

    【讨论】:

    • 我被困在同一个问题上,你的回答对我有帮助,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-12-28
    • 2018-07-27
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2018-05-17
    • 2019-12-06
    • 2019-01-17
    相关资源
    最近更新 更多