Inspiration for Custom Decorators in Angular

Netanel Basal
Netanel Basal
Published in
2 min readMay 3, 2017

--

This post assumes that you at least have some working knowledge of Angular and Decorators.

If you have no prior knowledge on the subject, you can read the following articles:

NgLog Class Decorator

This decorator will be helpful for debugging purposes. We will log the ngOnInit, ngOnDestroy and ngOnChanges lifecycle hooks.

We just log the hook and calling the original method. Let’s use the decorator.

Throttle Method Decorator

This decorator will be helpful when working for example with scroll events.

We are using the throttle helper from lodash and replacing the original method with our “throttle” version. Let’s use the decorator.

Track Page Class Decorator

This decorator will be helpful when you need to report page visits to your analytics provider.

Based on the hook we can call the appropriate method from our Analytics service then invoke the original method.

Log Observable Property Decorator

This decorator will be helpful for debugging purposes. You can also achieve the same thing with a custom operator.

We can get the observable and add the do operator to log the value. Based on the value we can choose between console.table or console.log .

Let’s use the decorator.

Conclusion:

You can leverage decorators in your apps and create powerful things with them. Decorators are not only for frameworks or libraries, so be creative and start using them.

Follow me on Medium or Twitter to read more about Angular, JS and Vue.

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.