Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Double check - Angular directive
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 {}
@eneajaho
Copy link
Author

eneajaho commented Nov 25, 2021

Usage:

<button type="button" (doubleCheck)="removePackage(package)">
   <fa-icon [icon]="trashIcon" class="me-2"></fa-icon>
   <span>Remove selected package</span>
</button>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment