问题描述
我们有一个带有 required
验证的自动完成输入.当用户通过输入查询来搜索选项(但未选择任何选项)时,输入有效,即使它与任何建议选项都不匹配.
We have an autocomplete input with required
validation. When a user searches for an option by entering a query (but doesn't pick any of the options) then the input is valid, even though it doesn't match any of the suggested options.
我想要实现的是除非选择了建议的选项之一,否则不允许用户发布表单.我如何实现这一目标?
What I want to achieve is not permitting the user to post the form unless one of the suggested options is selected. How do I achieve this?
<mat-form-field>
<input matInput placeholder="Pick one" aria-label="pick one" [matAutocomplete]="auto" [formControl]="form.controls['SELECTBOX_VALUE']">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of myOptions | async" [value]="option.name"> <span>{{ option.name }}</span> </mat-option>
</mat-autocomplete>
</mat-form-field>
<small *ngIf="!form.controls['SELECTBOX_VALUE'].valid && form.controls['SELECTBOX_DEGER'].touched" class="mat-text-warn">Please select.</small>
ngOnInit() {
this.form = this.fb.group({
... some other fields
SELECTBOX_VALUE: [null, Validators.required]
});
我的 Autocomplate 过滤器代码非常简单:
My filter code for Autocomplate is pretty straight forward:
this.form.get('SELECTBOX_VALUE').valueChanges
.pipe(
startWith(''),
map(option => secenek ? this.doFilter(option) : this.options.slice())
);
doFilter (name: string) {
return this.myOptions.filter(option =>
option.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
推荐答案
对于那些可能需要类似方法的人.这是我的解决方案.我已根据需要构建了自定义验证规则.
For those who may need a similar approach. Here's my solution. I've built a custom validation rule according to my needs.
SELECTBOX_VALUE: [
null,
Validators.compose([
Validators.required,
FormCustomValidators.valueSelected(this.myArray),
]),
];
export class FormCustomValidators {
static valueSelected(myArray: any[]): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null => {
let selectboxValue = c.value;
let pickedOrNot = myArray.filter(
(alias) => alias.name === selectboxValue
);
if (pickedOrNot.length > 0) {
// everything's fine. return no error. therefore it's null.
return null;
} else {
//there's no matching selectboxvalue selected. so return match error.
return { match: true };
}
};
}
}
这篇关于Angular Material:如何根据建议的选项验证自动完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!