How to implement a debounce time in keyup event in Angular 6

后端 未结 7 2003
盖世英雄少女心
盖世英雄少女心 2020-12-05 17:57

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

相关标签:
7条回答
  • 2020-12-05 18:33

    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.

    0 讨论(0)
提交回复
热议问题