简体   繁体   English

输入去抖动角度为 2

[英]Input debounce with angular 2

In an application I need to send an event on input debounce.在应用程序中,我需要在输入去抖动时发送一个事件。

I'm trying this :我正在尝试这个:

   @ViewChild('messageInput') messageInput: ElementRef;
   private inputTimeOutObservable: any;

    setTypingTimeOut(){
          this.inputTimeOutObservable = Observable.fromEvent(this.messageInput.nativeElement, 'input')
            .map((event: Event) => (<HTMLInputElement>event.target).value)
            .debounceTime(1000)
            .distinctUntilChanged()
            .subscribe(data => {
              this.sendEvent();
            });
    }
    ngOnDestroy() {
        if (this.inputTimeOutObservable) {
          this.inputTimeOutObservable.unsubscribe();
          this.inputTimeOutObservable = null;
        }
      }

The input do other stuff but here it is :输入做其他事情,但这里是:

 <input #messageInput id="message" type="text" (ngModelChange)="inputTextChanges($event)"
               [(ngModel)]="messageValue" (keyup)='keyUp.next($event)'>

The event is not fired and I don't see why here.该事件没有被触发,我在这里不明白为什么。 Any idea ?任何的想法 ?

Based on you code, here's a working example:根据您的代码,这是一个工作示例:

component.html组件.html

<input #messageInput id="message" type="text" [(ngModel)]="messageValue">

component.ts组件.ts

import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {Observable} from "rxjs/Rx";

@Component({
  selector: 'app-input-debounce',
  templateUrl: './input-debounce.component.html',
  styleUrls: ['./input-debounce.component.css']
})
export class InputDebounceComponent implements OnInit {
  @ViewChild('messageInput') messageInput: ElementRef;
  public messageValue: string = "";
  private inputTimeOutObservable: any;

  constructor() {
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.setTypingTimeOut();
  }

  setTypingTimeOut() {

    this.inputTimeOutObservable = Observable.fromEvent(this.messageInput.nativeElement, 'input')
      .map((event: Event) => (<HTMLInputElement>event.target).value)
      .debounceTime(1000)
      .distinctUntilChanged()
      .subscribe(data => {
        console.log(this.messageValue);
        console.timeEnd("Input changed after."); // No matter how frequent you type, this will always be > 1000ms
        console.time("Input changed after."); // start track input change fire time
      });
  }

}

If you don't mind using a reactive form control you could do the following:如果您不介意使用反应式表单控件,您可以执行以下操作:

import { FormControl } from '@angular/forms';

public myCtrl: FormControl = new FormControl();
myCtrl.valueChanges.debounceTime(1000).subscribe(value => ...);

And your template gets cleaner:你的模板变得更干净:

<input #messageInput id="message" type="text" [formControl]="myCtrl">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM