角度和去抖动在AngularJS中,我可以使用ng-model选项去抖模型。ng-model-options="{ debounce: 1000 }"如何在Angular中去抖模型?我试图在文档中搜索debounce,但我找不到任何东西。https://angular.io/search/#stq=debounce&stp=1一个解决方案是编写我自己的去抖函数,例如:import {Component, Template, bootstrap} from 'angular2/angular2';// Annotation section@Component({
selector: 'my-app'})@Template({
url: 'app.html'})// Component controllerclass MyAppComponent {
constructor() {
this.firstName = 'Name';
}
changed($event, el){
console.log("changes", this.name, el.value);
this.name = el.value;
}
firstNameChanged($event, first){
if (this.timeoutId) window.clearTimeout(this.timeoutID);
this.timeoutID = window.setTimeout(() => {
this.firstName = first.value;
}, 250)
}}bootstrap(MyAppComponent);而我的HTML<input type=text [value]="firstName" #first (keyup)="firstNameChanged($event, first)">但是我正在寻找一个内置函数,Angular中有一个吗?
3 回答
一只甜甜圈
TA贡献1836条经验 获得超5个赞
它可以作为指令实施
import { Directive, Input, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';import { NgControl } from '@angular/forms';import 'rxjs/add/operator/debounceTime';import 'rxjs/add/operator/distinctUntilChanged';import { Subscription } from 'rxjs';@Directive({ selector: '[ngModel][onDebounce]',})export class DebounceDirective implements OnInit, OnDestroy { @Output() public onDebounce = new EventEmitter<any>(); @Input('debounce') public debounceTime: number = 300; private isFirstChange: boolean = true; private subscription: Subscription; constructor(public model: NgControl) { } ngOnInit() { this.subscription = this.model.valueChanges .debounceTime(this.debounceTime) .distinctUntilChanged() .subscribe(modelValue => { if (this.isFirstChange) { this.isFirstChange = false; } else { this.onDebounce.emit(modelValue); } }); } ngOnDestroy() { this.subscription.unsubscribe(); }}
用它就像
<input [(ngModel)]="value" (onDebounce)="doSomethingWhenModelIsChanged($event)">
组件样本
import { Component } from "@angular/core";@Component({ selector: 'app-sample', template: ` <input[(ngModel)]="value" (onDebounce)="doSomethingWhenModelIsChanged($event)"> <input[(ngModel)]="value" (onDebounce)="asyncDoSomethingWhenModelIsChanged($event)"> `})export class SampleComponent { value: string; doSomethingWhenModelIsChanged(value: string): void { console.log({ value }); } async asyncDoSomethingWhenModelIsChanged(value: string): Promise<void> { return new Promise<void>(resolve => { setTimeout(() => { console.log('async', { value }); resolve(); }, 1000); }); }}
添加回答
举报
0/150
提交
取消