I have an email field, and I added two validators(required, email), I want to check validation status on the input event to call API check dose a member of my system when it's valid, if it's invalid don't to call API and don't show error message on the page.
I will show error message on blur event(focusOut email's input),firstly I used formControl.validator(formControl) to trigger validators and check formControl.valid,I got valid status successful but it will show error message on the page because I subscribed statsuChange to show an error message when status equal to invalid.
currently, I save validators in a variable and pass to initEmailChaingeEvent() to check validation status without statusChange event. It's can work, but I think it's not a good way, here's an example of my implementation:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
public sampleForm;
@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
});
}
private initEmailChaingeEvent(arg: {
emailFC: FormControl,
validtors: any[]
}) {
Observable.fromEvent(this.emailElm.nativeElement , 'input')
.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 know is valid , I don't want to show error msg on UI
for (const validator of arg.validtors) {
const inValid = validator(arg.emailFC);
if (inValid) {
return;
}
}
// **do sometheng when all valid**
// call api ....
});
}
private initShowErrorMsgEvent(arg: {
fc: FormControl,
}) {
arg.fc.statusChanges
.subscribe((status) => {
if(status === 'inValid'){
// show error msg....
}
});
}
}
<form formGroupName="sampleForm">
<input formControlName="email" #emailElm />
</form>
from How can I get Validators from the formControl directly?

No comments:
Post a Comment