Created
November 25, 2021 12:06
-
-
Save eneajaho/7efbfdf73733311d6229b5de28e3abed to your computer and use it in GitHub Desktop.
Double check - Angular directive
This file contains hidden or 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 { | |
AfterViewInit, | |
Directive, | |
ElementRef, | |
EventEmitter, | |
HostListener, | |
Input, | |
NgModule, | |
Output, | |
Renderer2 | |
} from '@angular/core'; | |
@Directive({ | |
selector: '[doubleCheck]' | |
}) | |
export class DoubleCheckDirective implements AfterViewInit { | |
@Input() message?: string; | |
@Input() timeout = 2500; | |
@Output() doubleCheck = new EventEmitter<void>(); | |
isConfirmed = false; | |
private initialTextContent!: string | null; | |
@HostListener('click', [ '$event' ]) clicked(): void { | |
if (this.isConfirmed) { | |
this.doubleCheck.emit(); | |
this.setContent(this.initialTextContent); | |
this.isConfirmed = false; | |
} else { | |
this.setContent(this.message ?? 'Are you sure?'); | |
this.isConfirmed = true; | |
setTimeout(() => { | |
this.setContent(this.initialTextContent); | |
this.isConfirmed = false; | |
}, this.timeout) | |
} | |
} | |
constructor(private elRef: ElementRef, private renderer: Renderer2) {} | |
ngAfterViewInit(): void { | |
this.initialTextContent = this.elRef.nativeElement.innerHTML; | |
} | |
setContent(text: string | null): void { | |
this.renderer.setProperty(this.elRef.nativeElement, 'innerHTML', text); | |
} | |
} | |
@NgModule({ | |
exports: [ DoubleCheckDirective ], | |
declarations: [ DoubleCheckDirective ], | |
}) | |
export class DoubleCheckModule {} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: