Skip to content

Instantly share code, notes, and snippets.

@takuya-nakayasu
Last active December 8, 2018 08:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save takuya-nakayasu/5b541395d8ed0214f1961dedc1132922 to your computer and use it in GitHub Desktop.
ボタンの連打を防止するAngularのディレクティブ
import { Directive, Input, ElementRef, HostListener } from '@angular/core';
/**
* 二重送信防止ディレクティブ
*
*/
@Directive({
selector: '[appDoubleClickPrevention]'
})
export class DoubleClickPreventionDirective {
// HTTP通信中フラグ
@Input('appDoubleClickPrevention') public isLoading: boolean;
constructor(private el: ElementRef) { }
/**
* 二重クリック防止のため、通信中はボタンをdisableに設定する。
*
*/
@HostListener('click') public onClick() {
// ボタンのdisabledをONにする
this.el.nativeElement.disabled = true;
setTimeout(() => this.releaseDisable(), 1000);
}
/**
* 500ミリ秒ごとにHTTP通信が完了したか確認する
*
*/
private releaseDisable() {
setInterval(() => {
if (!this.isLoading) {
// HTTP通信中でない場合、
// ボタンのdisableを解除する
this.el.nativeElement.disabled = false;
}
} , 500);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment