Sunday, February 4, 2024

Decorators in Angular

Decorators in Angular

There are several important concepts in Angular, and Decorators are an important concept to learn when you are working Angular. Decorators in Angular are a powerful and essential feature used to enhance and modify the behavior of classes, methods, and properties. Through this post we will learn about decorators, its types and how it is being used in real time applications.

What are Decorators?

Decorators are functions that are invoked with a prefixed @ symbol.Basically, a decorator provides configuration metadata that determines how the component, class or a function should be processed, instantiated and used at runtime.Decorators are applied to classes, class properties, and class methods using the following syntax:

@DecoratorName(arguments)

Angular comes with several built-in decorators, and you can also create custom decorators to extend or modify the behavior of your application.

Types of Decorators

There are four types of decorators and each type further has its own subset of decorators.

  1. Class Decorators

    This is the initial type of decorator that informs us about a specific class's purpose and helps clarify if the class is a component or a module. Angular has different class decorators, and two commonly used ones are @Component and @NgModule.The below code snippet uses @Component, which is a type of class decorator provided by Angular.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-example',
      template: '<p>This is an example component</p>',
    })
    export class ExampleComponent {}
          
  2. Property Decorators

    Property decorators are employed to enhance specific properties within a class. With a property decorator, we can clearly understand the purpose of using a particular property in a class, such as @Input(), @Output, @ReadOnly(), @Override().

    import { Component, Input, Output, EventEmitter } from '@angular/core';
    
    @Component({
      selector: 'app-child',
      template: '<p>{{ childData }}</p>',
    })
    export class ChildComponent {
      @Input() childData: string;
      @Output() dataChanged = new EventEmitter<string>();
    }
        
  3. Method Decorator

    Method decorators are used to add functionality to methods within a class. An example of a method decorator is @HostListener.

    import { Component, HostListener} from '@angular/core';
    
    @Component({
      selector: 'app-example',
      template: '<p>This is an example component</p>',
    })
    export class ExampleComponent {
      @HostListener('click',['event'])
      onHostClick(event:Event) {
      // your code
      }
    }      
  4. Parameter Decorator

    Parameter decorators let us decorate parameters in class constructors. A commonly used parameter decorator is @Inject(). It helps inject services into Angular classes.

    import { Component, Inject} from '@angular/core';
    import { MyService} from './my-service';
    @Component({
      selector: 'app-example',
      template: '<p>This is an example component</p>',
    })
    export class ExampleComponent {
      constructor(@Inject(MyService) myService){
      console.log(myService);
      }
    }

Creating Custom Decorators

You can also create your own decorators to add custom behavior to your classes. Here's a simple example:

function log(message: string) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log(`${message} ${propertyKey}`);
  };
}

class ExampleClass {
  @log('Executing')
  exampleMethod() {
    // Method logic
  }
}

const instance = new ExampleClass();
instance.exampleMethod(); // This will log "Executing exampleMethod"

In this example, the log decorator is a custom decorator that logs a message when the exampleMethod is executed.

Decorators play a crucial role in Angular's architecture, allowing for a clean and modular design of components, directives, and services. Understanding how to use and create decorators is essential for Angular developers to build scalable and maintainable applications.

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top