Skip to content

Instantly share code, notes, and snippets.

@eneajaho
Created November 25, 2021 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneajaho/7efbfdf73733311d6229b5de28e3abed to your computer and use it in GitHub Desktop.
Save eneajaho/7efbfdf73733311d6229b5de28e3abed to your computer and use it in GitHub Desktop.
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

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