Open In App

What are decorators in Angular?

In Angular decorators are important for defining and configuring various application elements, providing an easy way to enhance the classes with additional functionality and provide metadata. In this article, we'll take a detailed look at the concept of Decorators in Angular.

What are Decorators in Angular?

In Angular, decorators are functions that are used to modify the behavior of classes and their members. They provide a way to add metadata or apply transformations to code elements. In Angular, decorators are extensively used to define components, services, directives, pipes, modules, and more.

Types of Decorators in Angular

In Angular, there are four main types of decorators-

  1. Class Decorators: Class decorators are applied to classes to modify their behavior or metadata. The examples include @Component, @Directive and @NgModule.
  2. Property Decorators: Property decorators are applied to the class properties and are commonly used to modify the properties within the classes. For example, @Input decorator makes a property as an input binding, allowing it to bound to the external data.
  3. Method Decorators: Method decorators are applied to the class methods and modify their behavior or add additional functionalities. For example, @HostListener allows us to listen for events on a method.
  4. Parameter Decorators: The Parameter decorators are used for parameters inside class constructors. The parameter decorators provide additional information about constructor parameters. For example, The @Inject decorator allows to specify dependencies for dependency injection.

Uses of Decorators in Angular

Examples

1. @Component Decorator:

In this example we'll a look at the @Component decorator to define a simple angular component. This decorator provides metadata such as component's selector, template and styles. The @Component decorator informs the Angular's compiler how to process the Component.

Step 1: Create a new Angular project using the following command.

ng new my-app

Step 2: move to the project directory using the below command.

cd my-app

Step 3: Create a new component 'GreetingComponent' using the below command.

ng generate component Greeting

Folder Structure:


serdgf

What are decorators in Angular?


Dependencies:

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Step 4: Apply the below changes to the Greeting component.

<!-- app.component.html -->

<app-greeting></app-greeting>
//greeting.component.ts

import { Component } from '@angular/core';

@Component({
    selector: 'app-greeting',
    standalone: true,
    imports: [],
    template: '<h1>{{greeting}} from GeeksForGeeks!</h1>',
    styleUrl: './greeting.component.css',
})
export class GreetingComponent {
    greeting: string = 'Hello';
}
//app.component.ts

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { GreetingComponent } from './greeting/greeting.component'

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, GreetingComponent],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
})
export class AppComponent {
    title = 'my-app';
}

Step 5: Apply and save all the changes and run the application using the following command.

ng serve

Output:

Angular Decorator Example

output for example 1

2. Creating a Custom Decorator:

In this example, we'll create a custom '@Log' decorator that logs method invocations along with the parameters and the return values.

Step 1: Create a TypeScript class using the following command.

ng generate class log.decorator

Step 2: Create a example component to use the decorator using the following command.

ng generate component example

Folder Structure:

werth


Step 3: Update the following files with these codes.

<!-- app.component.html -->

<app-example></app-example>
//app.component.ts

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ExampleComponent } from './example/example.component'

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, ExampleComponent],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
})
export class AppComponent {
    title = 'my-app';
}
//example.component.ts

import { Component } from '@angular/core';
import { Log } from '../log.decorator';

@Component({
    selector: 'app-example',
    standalone: true,
    imports: [],
    template:
        '<h1>GeeksForGeeks</h1><button (click)="displayMessage()">Display</button>',
    styleUrl: './example.component.css',
})
export class ExampleComponent {
    @Log
    displayMessage() {
        return 'Hello from GeeksFromGeeks!';
    }
}
//log.decorator.ts

import { Injectable } from '@angular/core';
export function Log(target: any, key: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function (...args: any[]) {
        console.log(
            `[${target.constructor.name}] ${key} called with arguments:`,
            args,
        );
        const result = originalMethod.apply(this, args);
        console.log(`[${target.constructor.name}] ${key} returned:`, result);
        return result;
    };

    return descriptor;
}

Step 4: Apply and save all the changes and run the application using the following command.

ng serve

Output:

Creating Angular decorator example - output

output for example 2

Article Tags :