Reputation: 193
I went through lots of post, but did not find what I was looking for.
Basically,
I am showing user validation on form changes. My template looks like this:
<div class="form-group"
[class.error]="!loginForm.find('email').valid && loginForm.find('email').touched">
<div class="input-wrapper">
<input type ="email"
class="form-control"
id="email-input"
placeholder="Email"
formControlName="email">
</div>
<div *ngIf="loginForm.controls['email'].dirty && !loginForm.controls['email'].valid"
class="alert-msg">Email is invalid</div>
</div>
And, looking at other posts, my TS which debounces form is this:
this.loginForm.valueChanges.debounceTime(500).subscribe(form => {
console.log(form, this.loginForm);
});
Now, the console logs are actually debouncing. But, the validation message does not debounce. It shows up straight away the message.
Is there a way to overcome this issue?
Thanks, for stopping by,
Upvotes: 7
Views: 4974
Reputation: 721
I believe the debounceTime will only affect the code you have in the response form => { ... }
.
So what you could do is set the validation there:
private loginFormIsValid:boolean;
private emailIsNotValid:boolean;
ngOnInit() {
this.loginForm.valueChanges.debounceTime(500).subscribe(form => {
this.loginFormIsValid = !loginForm.find('email').valid
&& loginForm.find('email').touched;
this.emailIsNotValid = loginForm.controls['email'].dirty
&& !loginForm.controls['email'].valid;
console.log(form, this.loginForm);
});
}
...And then you would use it in you template as follows:
<div class="form-group" [class.error]="!loginFormIsValid">
<div class="input-wrapper">
<input type ="email"
class="form-control"
id="email-input"
placeholder="Email"
formControlName="email">
</div>
<div *ngIf="emailIsNotValid"
class="alert-msg">Email is invalid</div>
</div>
You can take a look at a post on debouncing, it's a good example.
Upvotes: 5