I create an Angular app that search students from API. It works fine but it calls API every time an input value is changed. I\'ve done a research that I need something calle
user.component.html
<input type="text" #userNameRef class="form-control" name="userName" > <!-- template-driven -->
<form [formGroup]="regiForm">
email: <input formControlName="emailId"> <!-- formControl -->
</form>
user.component.ts
import { fromEvent } from 'rxjs';
import { switchMap,debounceTime, map } from 'rxjs/operators';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(private userService : UserService) { }
@ViewChild('userNameRef') userNameRef : ElementRef;
emailId = new FormControl();
regiForm: FormGroup = this.formBuilder.group({
emailId: this.bookId
});
ngOnInit() {
fromEvent(this.userNameRef.nativeElement,"keyup").pipe(
debounceTime(3000),
map((userName : any) =>userName.target.value )
).subscribe(res =>{
console.log("User Name is :"+ res);
} );
//--------------For HTTP Call------------------
fromEvent(this.userNameRef.nativeElement,"keyup").pipe(
debounceTime(3000),
switchMap((userName : any) =>{
return this.userService.search(userName.target.value)
})
).subscribe(res =>{
console.log("User Name is :"+ res);
} );
----------
// For formControl
this.emailId.valueChanges.pipe(
debounceTime(3000),
switchMap(emailid => {
console.log(emailid);
return this.userService.search(emailid);
})
).subscribe(res => {
console.log(res);
});
}
*Note: make sure that your input element is not present in ngIf Block.