debounceTime
waits for the time period mentioned and then calls the subscribe method. e.g; debounceTime(1000)
will wait for 1 second. It is implemented through pipes
.
this can be added to any subscribe method. Following is the working example
import { Component, OnInit } from '@angular/core';
import { Validators, AbstractControl } from '@angular/forms';
import { debounceTime } from 'rxjs/operators';
// dynamic forms
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-customer-form',
templateUrl: './customer-form.component.html',
})
export class CustomerFormComponent implements OnInit {
emailMessage : string;
private validationMessages = {
required: "Email field is required",
email: "Please enter a valid Email"
}
customerForm: FormGroup;
customer = new Customer();
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.customerForm = this.fb.group({
emailAddress: ['',
[
Validators.required,
Validators.email
]
]
})
const emailControl = this.customerForm.get('emailAddress');
emailControl.valueChanges.pipe( debounceTime(1000) ).subscribe(
value => this.setEmailMessage(emailControl)
)
}
setEmailMessage( c: AbstractControl ) : void {
this.emailMessage = '';
if ( (c.touched || c.dirty) && c.errors ) {
this.emailMessage = Object.keys(c.errors).map( key => this.validationMessages[key]).join(' ');
}
}
}
in your template
<input
class="form-control"
id="emailId" type="email"
placeholder="Email (required)"
formControlName="emailAddress"
[ngClass]="{ 'is-invalid': emailMessage }"/>
<span class="invalid-feedback">
{{ emailMessage }}
</span>