【发布时间】:2018-11-08 01:49:36
【问题描述】:
我正在构建一个使用Angular Material Autocomplete module 的表单。我从服务器加载选项,然后用输入过滤它们。效果很好,现在我想添加一个“清除”图标以在需要时清除该字段。
清除选项会清除该字段,但不会再次显示自动完成选项。当我手动删除带有退格而不是图标的输入内容时,它会显示它们。
要“清除”我使用此代码的字段:
clear(control: string): void {
this.form.get(control).setValue('');
}
我从 mat-icon 组件调用它:
<mat-form-field>
<input matInput type="text" ... >
<mat-icon matSuffix (click)="clear(fieldName)" ...>
clear</mat-icon>
</mat-form-field>
<mat-autocomplete> ... </mat-autocomplete>
其中 fieldName (string) 是我要清除的控件的名称。
这就是我过滤自动完成选项的方式:
this.filter = this.form.get(field).valueChanges.pipe(
startWith(''), // Don't even know what this does...
map(value => this.options.filter(option => option.name.toLowerCase().includes(value.toString().toLowerCase())))
);
我怀疑clear() 方法中的setValue('') 可能存在错误。或者可能是我正在使用的过滤方法。
这是 StackBlitz 中的完整示例:
https://stackblitz.com/edit/angular-autocomplete-clear9zzmw2
【问题讨论】:
-
我看到即使在我使用清除按钮后,选择仍然显示选项,但我需要取消对选择的关注,然后再次关注它;您想在单击清除按钮后立即显示选项吗?