Angular 2 change event on every keypress

后端 未结 11 1413
说谎
说谎 2020-11-27 09:36

The change event is only called after the focus of the input has changed. How can I make it so that the event fires on every keypress?



        
11条回答
  •  执念已碎
    2020-11-27 10:19

    A different way to handle such cases is to use formControl and subscribe to it's valueChanges when your component is initialized, which will allow you to use rxjs operators for advanced requirements like performing http requests, apply a debounce until user finish writing a sentence, take last value and omit previous, ...

    import {Component, OnInit} from '@angular/core';
    import { FormControl } from '@angular/forms';
    import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
    
    @Component({
      selector: 'some-selector',
      template: `
        
      `
    })
    export class SomeComponent implements OnInit {
      private searchControl: FormControl;
      private debounce: number = 400;
    
      ngOnInit() {
        this.searchControl = new FormControl('');
        this.searchControl.valueChanges
          .pipe(debounceTime(this.debounce), distinctUntilChanged())
          .subscribe(query => {
            console.log(query);
          });
      }
    }
    

提交回复
热议问题