In Angular, @Component, @Injectable etc are built in decorator. However, you can also write your custom decorator. Such functions let you wrap up repetitive logic in reusable functions and thus help to improve code reusability and their maintainability.
In other words a custom decorator is a function we can invoke on top of a class, property or method to provide metadata or change their originating behaviour. After that you follow the same syntax as Angular’s built in decorators but you define your own logic.
Reusability: Encapsulate repetitive logic in one place.
It makes sure that the code is free of boilerplate code and keep components clean.
Force the same behaviour throughout several components or services.
The simple logging decorator we want to build will also log the method call as well as the arguments passed to them.
export function LogMethod() {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${propertyKey} with arguments:`, args);
const result = originalMethod.apply(this, args);
console.log(`Result of ${propertyKey}:`, result);
return result;
};
return descriptor;
};
}
import { Component } from '@angular/core';
import { LogMethod } from './log-method.decorator';
@Component({
selector: 'app-demo',
template: `<button (click)="calculate(5, 3)">Calculate</button>`
})
export class DemoComponent {
@LogMethod()
calculate(a: number, b: number): number {
return a + b;
}
}
When you click the button, you’ll see logs like:
Calling calculate with arguments: [5, 3]
Result of calculate: 8
Angular custom decorator is a way to add our own logical to class, method, properties. A good written code is only a code that is tidy, consistent and maintainable.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
Contact Us