其他分享
首页 > 其他分享> > angular 防抖点击

angular 防抖点击

作者:互联网

1.创建指令文件

ng g directive DebounceClickDirective --module=app

2.debounce-click-directive.directive.spec.ts 检查,确保导入正确

3.debounce-click-directive.directive.ts 文件代码

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

@Directive({
  selector: '[appDebounceClick]'
})
export class DebounceClickDirective implements OnInit {
  @Input() debounceTime = 500;
  @Output() debounceClick = new EventEmitter();
  private clicks = new Subject();
  private subscription: Subscription;

  constructor() { }

  ngOnInit() {
    this.subscription = this.clicks.pipe(
      debounceTime(this.debounceTime)
    ).subscribe(e => this.debounceClick.emit(e));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

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

 

4.HTML中使用

  <button (click)="myappDebounceClick()">即刻執行</button>
  <button appDebounceClick (debounceClick)="myappDebounceClick()">使用默認時間間隔來執行</button>
  <button appDebounceClick (debounceClick)="myappDebounceClick()" [debounceTime]="2000">自定義時間執行Debounced12
    Click</button>

 

5. 我的是分模块的,所以用的时候,需要把指令导入到shared.module.ts

 

 

 

 

 

 

6.然后需要使用的页面中使用,需要在对应的module.ts中引用shared

原文地址:https://www.cnblogs.com/sugartang/p/12485053.html

标签:防抖,directive,執行,ts,event,点击,debounceTime,import,angular
来源: https://www.cnblogs.com/zhawei/p/13032735.html