The Superpower of Typescript Decorators using angular

Learn how to build a reusable confirmation dialog using Typescript decorators.

The Superpower of Typescript Decorators using angular

Typescript decorators is one of the magical feature in the typescript. We can see decorators all over in Angular. We will learn how to build confirmation dialog using custom decorator in Angular.

What is Decorator

Typescript decorator extends the functionality using its metadata. it can used in  multiple place to alter the functionality.

  • class definitions
  • methods
  • properties
  • accessors
  • parameters

Without using custom decorator

addToCard(product: Production) {
    if(confim("Are you sure, do you want to add this product in cart!")) {
        this.cart.push(product);
    }
}
Custom typescript code

Using custom decorator

@Confirmable("Are you sure, do you want to add this product in cart!");
addToCard(product: Production) {
    this.cart.push(product);
}

Custom typescript decorator for display confirm dialog

We need to first create factory function to build our custom method decorator.

function Confirmable(message: string) {
    return function(target: Object, key: string | symbol, descriptor: PropertyDescriptor) {
        // login goes here
    }
}
Custom typescript decorator function
@message input passed in decorator function
@target component object
@key method name
@descriptor actual function it self

We need to extend the descriptor(function) with confirm dialog feature.

function Confirmable(message: string) {
    return function(target: Object, key: string | symbol, descriptor: PropertyDescriptor) {
        const fn = descriptor.value;
        
        descriptor.value = function(...args: any[]) {
            const allow = confrim(message);
            
            if(allow) {
                const result = fn.apply(this, args);
                return result
            } else {
                return null;
            }
        }
        
        return descriptor;
    }
}
Custom typescript decorator function for displaying dialog function

Now we can use decorator

@Confirmable("Are you sure, do you want to add this product in cart!");
addToCard(product: Production) {
    this.cart.push(product);
}

Different use case

@Confirmable("do you want to remove this product from the cart?");
removeFromCart(product: Production) {
    this.cart = this.filter(item => item !== product);
}

Conclusion

Hopefully you have learned how to use typescript decorators using angular. If you like the article please share with your network.

Documentation - Decorators
TypeScript Decorators overview