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:


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.

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

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

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

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

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:


Step 3: Update the following files with these codes.

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

<app-example></app-example>
JavaScript
//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';
}
JavaScript
//example.component.ts

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

@Component({
    selector: 'app-example',
    standalone: true,
    imports: [],
    template:
        '<h1>w3wiki</h1><button (click)="displayMessage()">Display</button>',
    styleUrl: './example.component.css',
})
export class ExampleComponent {
    @Log
    displayMessage() {
        return 'Hello from GeeksFromGeeks!';
    }
}
JavaScript
//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:

output for example 2



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.

Table of Content

  • What are Decorators in Angular?
  • Types of Decorators in Angular
  • Uses of Decorators in Angular
  • Examples

Similar Reads

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-...

Uses of Decorators in Angular

Component Configuration: Use @Component to define the metadata of Angular components, including template, styles, and selector.Service Definition: Mark a class with @Injectable to make it injectable as a service throughout the application.Directive Behavior: Implement @Directive to attach custom behavior to elements in the DOM.Pipe Transformation: Utilize @Pipe to define custom data transformation logic for templates.Module Organization: Use @NgModule to structure Angular modules and manage dependencies.Input and Output Handling: Use @Input and @Output to pass data between parent and child components.View Management: Utilize @ViewChild and @ViewChildren to access child components or elements in the view....

Examples

1. @Component Decorator:...

Contact Us