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,
Debounce Time is the delay which we can add between event subscriptions. Like we can add Debounce Time of 1000 milliseconds which resets after every KeyUp event by a user, if the gap of time between KeyUp event exceeds the 1000 ms then we make a subscription or make API call.
In JavaScript, a debounce function makes sure that your code is only triggered once per user input. Search box suggestions, text-field auto-saves, and eliminating double-button clicks are all use cases for debounce.
Debouncing is the delay of a function/method execution or an action for a period of the specified time. During this specified time, calls to the method/function or action are collected and executes each one when the specified has elapsed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With