What are decorators in Angular?
Last Updated :
18 Apr, 2024
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-
- Class Decorators: Class decorators are applied to classes to modify their behavior or metadata. The examples include @Component, @Directive and @NgModule.
- 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.
- 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.
- 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
- 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:
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 GeeksForGeeks!</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 12. 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>GeeksForGeeks</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
Similar Reads
What are Directives in AngularJS ?
AngularJS directives are extended HTML attributes having the prefix ng-. Directives are markers on the DOM element which tell Angular JS to attach a specified behavior to that DOM element or even transform the DOM element with its children. During compilation, the HTML compiler traverses the DOM mat
7 min read
Input Decorator In Angular
The @Input decorator in Angular is used to pass data from the parent to child components. It allows a parent component to bind data to properties in a child component enabling the sharing of data between components in a hierarchical relationship. The @Input decorator is important for communication b
4 min read
What are expressions in AngularJS ?
In this article, we will see the expressions in Angular JS, along with knowing the different methods for implementing it through the code examples. Expressions in AngularJS, are the statements that are to be evaluated, that is placed inside the double curly braces. The result of the evaluation will
5 min read
What are angular Material Icons ?
Angular Material is a UI component library which is developed by Google so that Angular developers can develop modern applications in a structured and responsive way. By making use of this library, we can greatly increase the user experience of an end-user thereby gaining popularity for our applicat
3 min read
Angular ViewChildren Decorator
The ViewChildren decorator in Angular is used to query multiple elements or directives in the view DOM and gain a reference to them. It is particularly useful when you want to interact with multiple elements of the same type or group within a template. The ViewChildren decorator returns a QueryList
6 min read
What are templates in AngularJS ?
Templates in AngularJS are simply HTML files filled or enriched with AngularJS stuff like attributes and directives. A directive is a marker element that is used to target a particular attribute or class to render its behavior according to the needs. Model and controller in Angular are combined with
3 min read
What are providedIn strings in Angular?
Angular's dependency injection (DI) system is a powerful feature that provides the management of application-wide services. Among these, providedIn stands out as a concise and efficient way to specify where and how services should be injected within an Angular application. In this article, we'll see
3 min read
What is Angular Material?
User Experience is one of the most important things in web development. Angular Material emerges as a powerful tool for developers, offering numerous UI components designed to elevate your Angular applications to new heights of elegance and functionality. In this article, we'll learn more about Angu
4 min read
Closures And Decorators In Python
Closures and decorators are powerful features in Python that allow for more advanced and flexible code patterns. Understanding these concepts can greatly enhance your ability to write clean, efficient, and reusable code. Why Python decorators rather than closures?Python decorators are preferred over
3 min read
Attribute Directives in Angular
Attribute directives are a powerful tool that allows you to manipulate the behavior and appearance of HTML elements. In this article, you will see the fundamentals of attribute directives. Table of Content What are Attribute Directive?Benefits of Attribute DirectiveTypes of Attribute DirectivesSteps
5 min read