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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...