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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。