Created
December 4, 2023 10:55
-
-
Save antoine1003/1effc9a284fba3e0dd5acef78fcdf070 to your computer and use it in GitHub Desktop.
An Angular directive to make a loading button. It adds a loading icon at the beggining of the button when the appBtnLoading is true.
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, ElementRef, Input, OnChanges, Renderer2, SimpleChanges } from '@angular/core'; | |
@Directive({ | |
selector: '[appBtnLoading]' | |
}) | |
export class BtnLoadingDirective implements OnChanges { | |
@Input({required: true}) | |
appBtnLoading = false; | |
private readonly _LOADING_INDICATOR_ELEMENT!: HTMLElement; | |
constructor(private readonly targetEl: ElementRef, private readonly renderer: Renderer2) { | |
this._LOADING_INDICATOR_ELEMENT = this._getLoadingNode(); | |
} | |
ngOnChanges(changes: SimpleChanges): void { | |
if ('appBtnLoading' in changes) { | |
const native = this.targetEl.nativeElement as HTMLElement; | |
if (changes['appBtnLoading'].currentValue === true) { | |
native.setAttribute('disabled', 'true'); | |
this.renderer.setStyle(native, 'display', 'flex'); | |
this.renderer.setStyle(native, 'flex-direction', 'row-reverse'); | |
this.renderer.setStyle(native, 'align-items', 'center'); | |
this.renderer.appendChild(native, this._LOADING_INDICATOR_ELEMENT) | |
} else { | |
native.removeAttribute('disabled'); | |
this.renderer.removeStyle(native, 'display'); | |
this.renderer.removeStyle(native, 'flex-direction'); | |
this.renderer.removeStyle(native, 'align-items'); | |
this.renderer.removeChild(native, this._LOADING_INDICATOR_ELEMENT); | |
} | |
} | |
} | |
private _getLoadingNode(): HTMLElement { | |
const icon = document.createElement('i'); | |
icon.classList.add('las', 'la-circle-notch', 'la-spin', 'mr-2'); // Using https://icons8.com/line-awesome | |
return icon; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The usage is simple :
Where
isLoading
is your component property. This directive will also disable the button ifisLoading
is true.