去抖动以获取 angular2 中的值输入

Sal*_*lma 12 angular

当自定义写入输入但不等待他单击按钮时,我想在 angular 2 的几个时间(许多毫秒或秒)后从输入文本中获取一个值。

我试过这个,但即使我使用debounceTime,每次按键都会发送值。

我尝试了解 debounce 和 observable,这就是我的理解,任何人都可以帮我修复我的代码:

组件.html:

<md-card-title *ngIf="!edit">{{card.title}}</md-card-title>
 <input *ngIf="edit" type="text" [(ngModel)]="card.title" (ngModelChange)='rename()'/>
Run Code Online (Sandbox Code Playgroud)

组件.ts

newTitle: string;
modelChanged: Subject < string > = new Subject < string > ();

constructor()
this.modelChanged
  .debounceTime(500) //before emitting last event
  .distinctUntilChanged()
  .subscribe(model => this.newTitle = model);
}

rename(): void {
  this.renameRequest.emit(this.newTitle);
}
Run Code Online (Sandbox Code Playgroud)

Mil*_*lad 9

好吧,有很多方法可以实现这一目标,但这里有一种方法:

<input *ngIf="edit" type="text" #input="ngModel" [(ngModel)]="card.title" (ngModelChange)='rename()'/>
Run Code Online (Sandbox Code Playgroud)

在你的课堂上

newTitle : string;
@ViewChild('input') input;
constructor()

}

ngAfterViewInit(){
       this.input.valueChanges
             .pipe(debounceTime(500)) before emitting last event
             .pipe(distinctUntilChanged())
             .subscribe(model => (value)=>{
                   console.log('delayed key press value',value);
                    this.rename(value)
              });

}

rename(value): void {
    this.renameRequest.emit(value);
}
Run Code Online (Sandbox Code Playgroud)

这是Plunker

您甚至可以像下面这样订阅 modelChange :

ngAfterViewInit(){
       this.input.update // this is (modelChange)
             .pipe(debounceTime(500)) before emitting last event
             .pipe(distinctUntilChanged()) 
             .subscribe(model => (value)=>{
                   console.log('delayed key press value',value);
              });

}
Run Code Online (Sandbox Code Playgroud)

  • 在更新的 angular 版本中,你需要 `pipe()` 它看起来像:`this.input.valueChanges.pipe(debounceTime(500), distinctUntilChanged()).subscribe` (5认同)