Skip to content

Instantly share code, notes, and snippets.

@antoine1003
Created December 4, 2023 10:55
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 antoine1003/1effc9a284fba3e0dd5acef78fcdf070 to your computer and use it in GitHub Desktop.
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.
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;
}
}
@antoine1003
Copy link
Author

The usage is simple :

<button [appBtnLoading]="isLoading">Foo</button

Where isLoading is your component property. This directive will also disable the button if isLoading is true.

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