Last active
December 8, 2018 08:38
Star
You must be signed in to star a gist
ボタンの連打を防止するAngularのディレクティブ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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