Angular 角度4 FormGroup值匹配数组项
我想为我的表单组创建一个自定义验证函数,用于验证与我的国家/地区列表项匹配的国家/地区的输入 这是我的国家名单:Angular 角度4 FormGroup值匹配数组项,angular,Angular,我想为我的表单组创建一个自定义验证函数,用于验证与我的国家/地区列表项匹配的国家/地区的输入 这是我的国家名单: this.sharedService.getCountry().subscribe(res => { res.map(item => { this.countryList.push(item); }); }); 我的表格是: this.form = fb.group({ country: new FormControl('', [Validato
this.sharedService.getCountry().subscribe(res => {
res.map(item => {
this.countryList.push(item);
});
});
我的表格是:
this.form = fb.group({
country: new FormControl('', [Validators.required]),
});
您需要编写一个自定义验证器服务来检查输入,如下所示:
function check_if_valid(value,array){
if((alue){
const isInArray = array.includes(value);
return true;
} else {
return false;
}
}
@Injectable()
export class ValidatorsService {
public isInteger = (control:FormControl) => {
return check_if_valid(control.value,yourarray);
}
}
和在组件中
constructor(private _ValidatorsService: ValidatorsService){
}
country: new FormControl('', [Validators.required,this._ValidatorsService.isInteger ]),
那么我如何调用我的数组呢?我可以在构造函数()中调用它吗?你可以在服务本身中调用api,除非你没有在你的组件中使用。当我写这篇文章时,我会得到错误信息。_ValidatorsService.isInteger in formControlTS2345:类型为“((control:AbstractControl=>ValidationErrors)|((control:FormControl=>boolean))[]“”不可分配给类型为“ValidatorFn | ValidatorFn[]| AbstractControlOptions”的参数。类型“((控件:AbstractControl)=>ValidationErrors)((控件:FormControl)=>boolean))[]”与类型“AbstractControlOptions”没有共同的属性。