Inspiration for Custom Decorators in Angular
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:
- Make your Code Cleaner with Decorators
- Automagically Unsubscribe in Angular
- Decorators & metadata reflection in TypeScript: From Novice to Expert
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.