当前位置:   article > 正文

Angular+TS+Rxjs实现防抖的自定义指令_前端angular ts防抖怎么做

前端angular ts防抖怎么做

Angular防抖自定义指令

记录一下angular自定义指令

创建自定义指令文件debounce.directive.ts

import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Directive({
  selector: '[appDebounceClick]'
})
export class DebounceClickDirective implements OnInit, OnDestroy {
  @Input() public debounceTime = 500;
  @Output() public debounceClick = new EventEmitter();
  // tslint:disable-next-line
  private clicks = new Subject<any>();
  private subscription: Subscription;
  constructor() {}
  public ngOnInit(): void {
    this.subscription = this.clicks
      .pipe(debounceTime(this.debounceTime))
      .subscribe(e => this.debounceClick.emit(e));
  }
  public ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  @HostListener('click', ['$event'])
  public clickEvent(event: MouseEvent): void {
    event.preventDefault();
    event.stopPropagation();
    this.clicks.next(event);
  }
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

指令导出

import { NgModule } from '@angular/core';
import { DebounceClickDirective } from './debounce.directive';


@NgModule({
  declarations: [
    DebounceClickDirective
  ],
  exports: [
    DebounceClickDirective
  ],
})
export class SharedDirectivesModule {
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

实际使用

<span (debounceClick)="export()" appDebounceClick [debounceTime]="300">导出模版</span>
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/222984
推荐阅读
相关标签
  

闽ICP备14008679号