我有一个电子邮件字段,并添加了两个验证器(必需,电子邮件),我想在 输入事件
上检查验证状态,以在其有效时调用系统成员的 API 并检查,如果无效则不要调用 API 并且不要在页面上显示错误消息。
当焦点离开电子邮件字段时,我将在模糊事件(focusOut email's input)上显示错误消息,首先我使用formControl.validator(formControl)
来触发验证器并检查formControl.valid
,我成功地得到了有效状态,但它会在页面上显示错误消息,因为我已经订阅了statusChange
来在状态等于invalid
时显示错误消息。
目前,我将验证器保存在变量中,并传递给initEmailChaingeEvent()
以在不使用statusChange事件的情况下检查验证状态。
这样可以工作,但我认为这不是一个好方法。下面是我的实现示例:
export class AppComponent {
public sampleForm: FormGroup;
@ViewChild('emailElm')
emailElm: ElementRef;
ngOnInit() {
this.initForm();
}
initForm() {
const emailValidtors = [
Validators.required,
Validators.email
]
const emailFC = new FormControl(null, {
validators: emailValidtors,
updateOn: 'blur'
});
//
this.sampleForm = new FormGroup({
'email': emailFC
});
//
this.initEmailChaingeEvent({
emailFC: emailFC,
validtors: emailValidtors
});
//
this.sampleForm.valueChanges.subscribe((val) => {
console.log('_blue event:valueChanges', val)
});
//
this.initShowErrorMsgEvent({
fc: emailFC
});
}
private initEmailChaingeEvent(arg: {
emailFC: FormControl,
validtors: any[]
}) {
fromEvent(this.emailElm.nativeElement, 'input')
.pipe(debounceTime(500))
.subscribe((event: Event) => {
const currentEmail = (event.target as HTMLInputElement).value;
// check is valid
// **quention** : how can I get validtors from fromcontrol self
// if I use arg.emailFC.validator(arg.emailFC) to ehcek status , it will trigger oberservable in initShowErrorMsgEvent(),
// but I just want to got valid result , I don't want to show error msg on UI at this time
for (const validator of arg.validtors) {
const inValid = validator(arg.emailFC);
if (inValid) {
console.log('input event:invalid', currentEmail);
return;
}
}
// **do sometheng when all valid**
console.log('input event:call API , email:',currentEmail );
});
}
private initShowErrorMsgEvent(arg: {
fc: FormControl,
}) {
arg.fc.statusChanges
.subscribe((status) => {
// console.log('status' , status);
if (status === 'INVALID') {
// show error msg....
console.log('_show error msg by antoher component');
}
});
}
}
<form [formGroup]="sampleForm">
<input formControlName="email" #emailElm >
</form>
updateOn:blur'
,.valid
或.invalid
将不会在输入事件上触发。 - Chunbin Li