亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

角度和去抖動

角度和去抖動

紅顏莎娜 2019-08-12 10:45:05
角度和去抖動在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);
    });
  }}


查看完整回答
反對 回復 2019-08-12
  • 3 回答
  • 0 關注
  • 686 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號