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
Using custom decorator
We need to first create factory function to build our custom method decorator.
@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.
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.