DEV Community

Nigro Simone
Nigro Simone

Posted on

Enable / Disable Your Angular UI During Long Tasks with ng-lock

Introduction

Ever faced the issue where users click a button multiple times, causing chaos in your application? Meet ng-lock, the Angular library designed to save the day. It offers a straightforward way to lock functions and the user interface while a task is running. This guide will walk you through the installation, basic usage, and customization options of ng-lock.

Why Use ng-lock?

Key Benefits:

  • Prevents Multiple Clicks: Ensures a function executes only once until it completes, avoiding redundant operations.
  • User Interface Locking: Disables UI elements to signal an ongoing process, enhancing user experience.
  • Easy Integration: Simple decorators to lock and unlock functions, reducing boilerplate code.

Installation

Getting started with ng-lock is a breeze. Follow these simple steps to install and set it up in your Angular application.

Step 1: Install ng-lock
Open your terminal and run:

npm i ng-lock
Enter fullscreen mode Exit fullscreen mode

Step 2: Import and Use the Decorators
Here's a basic example to demonstrate how to lock a button click event.

import { Component } from '@angular/core';
import { ngLock, ngUnlock } from 'ng-lock';

@Component({
  selector: 'app-root',
  template: `<button (click)="onClick($event)">Click me!</button>`,
  styles: [`
    button.ng-lock-locked {
      pointer-events: none; 
      border: 1px solid #999999;
      background-color: #cccccc;
      color: #666666;
    }
  `]
})
export class AppComponent {

  @ngLock()
  onClick(event: MouseEvent) {
    // Simulate a long task
    setTimeout(() => {
      console.log("task ended");
      ngUnlock(this.onClick);
    }, 3000);
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the button will be locked (disabled) during the simulated long task (3 seconds).

Customizing ng-lock

ng-lock comes with several options to tailor its behavior to your needs. Here’s a deeper dive into the configuration.

Default Configuration

@ngLock({
  maxCall: 1,
  unlockTimeout: null,
  lockClass: 'ng-lock-locked',
  lockElementFunction: ngLockElementByTargetEventArgument(),
  returnLastResultWhenLocked: false,
  debug: false
})
onClick(event: MouseEvent) {
  setTimeout(() => {
    console.log("task executed");
    ngUnlock(this.onClick);
  }, 3000);
}
Enter fullscreen mode Exit fullscreen mode

Options Explained

  • maxCall: Number of calls before the function is locked. Default is 1.
  • unlockTimeout: Maximum time in milliseconds to lock the function. Default is null (no timeout).
  • lockClass: CSS class applied when the method is locked. Default is ng-lock-locked.
  • lockElementFunction: Function to find the HTML element to apply the lockClass. Default is ngLockElementByTargetEventArgument().
  • returnLastResultWhenLocked: If true, returns the last result when the method is locked. Default is false.
  • debug: Logs information to the console if true. Default is false.

Advanced Usage

Using lockElementFunction
You can customize the element that gets locked by defining your lockElementFunction. Here are a few examples:

Lock by Query Selector

@ngLock({
  lockElementFunction: ngLockElementByQuerySelector('.my-class')
})
onClick() {
  setTimeout(() => {
    console.log("task executed");
    ngUnlock(this.onClick);
  }, 3000);
}
Enter fullscreen mode Exit fullscreen mode

Lock by Component Property

@ViewChild("button") button: ElementRef<HTMLElement>;

@ngLock({
  lockElementFunction: ngLockElementByComponentProperty('button')
})
onClick() {
  setTimeout(() => {
    console.log("task executed");
    ngUnlock(this.onClick);
  }, 3000);
}
Enter fullscreen mode Exit fullscreen mode

Additional Utility Functions

ngUnlockAll
Unlocks all methods in a component.

ngUnlockAll(this);
Enter fullscreen mode Exit fullscreen mode

ngIsLock
Checks if a method is locked.

console.log('onClick is locked?', ngIsLock(this.onClick));
Enter fullscreen mode Exit fullscreen mode

Examples

Example with unlockTimeout

@ngLock({
  unlockTimeout: 3000
})
onClick(event: MouseEvent) {
  console.log("task executed");
}
Enter fullscreen mode Exit fullscreen mode

Example with maxCall

@ngLock({
  maxCall: 3
})
onClick(event: MouseEvent) {
  console.log("task executed");
}

onCheck() {
  console.log('onClick lock state:', ngIsLock(this.onClick));
}

onUnlock() {
  ngUnlock(this.onClick);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

ng-lock is a powerful yet simple library to enhance your Angular applications by controlling function execution and user interface interaction. By using decorators, it allows you to manage function calls efficiently, providing a seamless user experience. Give it a try and make your app smarter and more user-friendly!

Links:

Top comments (0)