[英]How to detect mat-autocomplete option is selected in Angular?
I tried this approach in order to apply validation to Material Autocomplete.我尝试这种方法是为了将验证应用于材料自动完成。 But the part used for detecting if the value is selected or not by comparing the type is not working:但是用于通过比较类型来检测值是否被选中的部分不起作用:
import { AbstractControl } from '@angular/forms';
export function RequireMatch(control: AbstractControl) {
const selection: any = control.value;
if (typeof selection === 'string') {
return { incorrect: true };
}
return null;
}
When debugging the app, typeof selection === 'string'
line always returns true - it doesn't matter if the option is selected or not.调试应用程序时, typeof selection === 'string'
行始终返回 true - 是否选择该选项无关紧要。 Any idea how to check it?知道如何检查吗? The testable app is available on StackBlitz .可测试的应用程序在StackBlitz上可用。
For me it works Just fine, as soon as you click the wanted option there is no error.对我来说它工作得很好,只要你点击想要的选项就没有错误。
note that you have to click on the wanted option and not just write it.请注意,您必须单击想要的选项,而不仅仅是编写它。
Normal with two error:正常,有两个错误:
With error "incorrect" if you don't select one of the options:如果您不选择以下选项之一,则会出现错误“不正确”:
Error still present if you type the option instead of clicking on it:如果您键入选项而不是单击它,错误仍然存在:
No error if you click on the wanted option:如果您单击想要的选项,则不会出错:
Just to add to this, I've modified the validator function to the following:只是为了添加到这一点,我已将验证器功能修改为以下内容:
private _autocompleteValidator(control: AbstractControl) {
return control.value && typeof control.value === 'string'
? { autocomplete: true }
: null;
}
Adding the control.value && ...
to the check allows for the input (whether partially typed or previously selected) to be cleared and pass validation.将control.value && ...
添加到检查中允许清除输入(无论是部分输入还是先前选择)并通过验证。
The purpose of this validator should only be to force the value to be a selection from the autocompleter, if a value is entered .如果输入了值,此验证器的目的应该只是强制该值成为自动完成器中的一个选择。
If the particular field in question is required, that should be configured through a separate, standard Validators.required
.如果需要特定字段,则应通过单独的标准Validators.required
进行配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.