Angular is a powerful front-end framework that helps developers build dynamic and efficient web applications. One of its key features is decorators, which play a crucial role in defining and configuring classes. In this article, we’ll explore what decorators are, their types, and how they work in Angular applications.
What Are Decorators in Angular?
Decorators in Angular are special functions that enhance classes by adding metadata. They allow Angular to understand how a class should behave and how it interacts with different elements in the application. Decorators are a part of TypeScript and use the @ symbol before the function name. They help define components, services, modules, directives, and more in an Angular application.
Types of Decorators in Angular
Angular provides several built-in decorator, categorized into four main types:
- Class Decorators – Define Angular classes like components, modules, and directives.
- Property Decorators – Define how class properties behave in Angular.
- Method Decorators – Modify functions in a class.
- Parameter Decorators – Configure parameters in class constructors.
Let’s explore each type in detail.
1. Class Decorators
Class decorators are used to define Angular classes such as components, modules, and directives. They provide metadata that tells Angular how to process the class.
@Component Decorator
Defines a component in Angular.
typescript
CopyEdit
import { Component } from ‘@angular/core’;
@Component({
selector: ‘app-example’,
template: `<h1>Hello, Angular!</h1>`,
styleUrls: [‘./example.component.css’]
})
export class ExampleComponent { }
- selector – Defines the HTML tag for this component.
- template – Specifies the HTML content.
- styleUrls – Links the CSS files.
@NgModule Decorator
Defines an Angular module that organizes components, directives, and services.
typescript
CopyEdit
import { NgModule } from ‘@angular/core’;
import { BrowserModule } from ‘@angular/platform-browser’;
import { AppComponent } from ‘./app.component’;
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- declarations – Lists the components and directives in the module.
- imports – Includes external modules.
- providers – Registers services.
- bootstrap – Specifies the main component.
@Directive Decorator
Defines custom directives in Angular.
typescript
CopyEdit
import { Directive, ElementRef, Renderer2 } from ‘@angular/core’;
@Directive({
selector: ‘[appHighlight]’
})
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer2) {
renderer.setStyle(el.nativeElement, ‘color’, ‘blue’);
}
}
- The directive appHighlight can be used in an HTML element to change its text color to blue.
2. Property Decorators
Property decorator define how properties behave within a class. They help inject dependencies and bind data.
@Input Decorator
Allows data to be passed from a parent component to a child component.
typescript
CopyEdit
import { Component, Input } from ‘@angular/core’;
@Component({
selector: ‘app-child’,
template: `<p>{{ message }}</p>`
})
export class ChildComponent {
@Input() message!: string;
}
- The message property receives data from the parent component.
@Output Decorator
Enables child components to send data back to the parent component using EventEmitter.
typescript
CopyEdit
import { Component, Output, EventEmitter } from ‘@angular/core’;
@Component({
selector: ‘app-child’,
template: `<button (click)=”sendMessage()”>Click Me</button>`
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit(‘Hello from Child Component!’);
}
}
- The child component emits an event when the button is clicked.
@HostBinding Decorator
Binds a property to a DOM element’s attribute.
typescript
CopyEdit
import { Directive, HostBinding } from ‘@angular/core’;
@Directive({
selector: ‘[appStyle]’
})
export class StyleDirective {
@HostBinding(‘style.color’) color = ‘red’;
}
- This directive changes the text color of the host element to red.
3. Method Decorators
Method decorator modify the behavior of class methods.
@HostListener Decorator
Listens for DOM events and triggers methods when the event occurs.
typescript
CopyEdit
import { Directive, HostListener } from ‘@angular/core’;
@Directive({
selector: ‘[appClick]’
})
export class ClickDirective {
@HostListener(‘click’) onClick() {
alert(‘Element clicked!’);
}
}
- When an element with appClick is clicked, an alert is shown.
4. Parameter Decorators
Parameter decorators define how dependencies are injected into constructors.
@Inject Decorator
Manually injects dependencies into a class.
typescript
CopyEdit
import { Component, Inject } from ‘@angular/core’;
import { LoggerService } from ‘./logger.service’;
@Component({
selector: ‘app-example’,
template: `<p>Check the console</p>`
})
export class ExampleComponent {
constructor(@Inject(LoggerService) private logger: LoggerService) {
this.logger.log(‘LoggerService injected!’);
}
}
- The LoggerService is manually injected into the component.
@Self Decorator
Ensures that a service is only injected from the local injector.
typescript
CopyEdit
import { Component, Self } from ‘@angular/core’;
import { LoggerService } from ‘./logger.service’;
@Component({
selector: ‘app-example’,
template: `<p>Example Component</p>`
})
export class ExampleComponent {
constructor(@Self() private logger: LoggerService) { }
}
- This prevents Angular from looking for the service in higher-level modules.
Why Are Decorators Important in Angular?
Decorators are essential in Angular for the following reasons:
- They simplify metadata declaration.
- They help Angular recognize components, directives, and modules.
- They enable dependency injection, making applications more modular and testable.
- They allow developers to extend and modify class behavior dynamically.
Conclusion
Decorator are a powerful feature in Angular that enhance classes by adding metadata and functionality. They allow developers to define components, modules, services, and directives efficiently. Understanding how decorator work is crucial for building scalable and maintainable Angular applications.
FAQs
What are decorators in Angular?
Decorators are special functions in TypeScript that provide metadata to Angular classes, helping Angular understand how to process them.
What is the difference between @Component and @Directive?
- @Component defines a full-fledged component with a template and logic.
- @Directive modifies existing elements without adding a separate template.
How does @Input differ from @Output?
- @Input passes data from a parent component to a child component.
- @Output allows a child component to send events to a parent component.
Why is @HostListener used in Angular?
@HostListener listens for DOM events and triggers specific methods when an event occurs.
Are decorators unique to Angular?
No, decorator are a TypeScript feature and are also used in other JavaScript frameworks and libraries.