Wae*_*ael 4 html angular-material angular
我有一个包含输入的 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>
Run Code Online (Sandbox Code Playgroud)
这是(模糊)事件的函数:
checkIfMatch() {
setTimeout(() => {
// . . .
}, 1000);
}
}
Run Code Online (Sandbox Code Playgroud)
您应该(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>
Run Code Online (Sandbox Code Playgroud)
文档:https : //material.angular.io/components/autocomplete/api#MatAutocompleteSelectedEvent
示例:Mat-autocomplete - 如何访问选定的选项?
我找到了我的问题的解决方案:对于模糊的调用,我添加了一个检查以查看事件的相关目标是否来自 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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10387 次 |
| 最近记录: |