Loading...

Decorators Reference

In Angular, decorators are a fundamental feature that allow developers to attach metadata to classes, properties, and methods, informing the framework how to process these entities within the application. Decorators are essential for building component-based architectures, managing state efficiently, controlling data flow, and handling component lifecycles in modern single-page applications (SPAs).
Angular’s core decorators include @Component, @Directive, @Pipe, @Injectable, and @NgModule. Each decorator serves a specific purpose: @Component defines a UI component, @Directive creates custom directives, @Pipe implements data transformation logic, @Injectable facilitates dependency injection, and @NgModule organizes related classes into cohesive modules. Additional decorators like @Input and @Output manage parent-child data binding and event communication, while @ViewChild and @ContentChild provide access to child components or projected content.
Mastering Angular decorators enables developers to create reusable, maintainable components with predictable state management and efficient data updates. This reference provides practical guidance on implementing decorators to handle component logic, event handling, and lifecycle interactions, while avoiding common pitfalls such as prop drilling, unnecessary re-renders, and direct state mutations. By the end of this guide, readers will understand how to leverage decorators to structure high-performance Angular applications, improve maintainability, and follow best practices in enterprise-level development.

Basic Example

typescript
TYPESCRIPT Code
import { Component, Input } from '@angular/core';

@Component({
selector: 'app-user-card',
template: `     <div class="card">       <h2>{{ name }}</h2>       <p>Age: {{ age }}</p>     </div>
`,
styles: [`     .card {
padding: 16px;
border-radius: 8px;
background-color: #f5f5f5;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
text-align: center;
}
`]
})
export class UserCardComponent {
@Input() name!: string;
@Input() age!: number;
}

In this basic example, the @Component decorator defines UserCardComponent as a reusable Angular component. The selector specifies the custom HTML tag, while the template and styles define its view and CSS. The @Input decorator allows the component to receive data from its parent, facilitating controlled state updates and preventing prop drilling.
The component lifecycle is managed by Angular, ensuring proper initialization, rendering, and destruction. Input bindings automatically update the view when parent data changes, minimizing unnecessary re-renders. This pattern demonstrates how decorators provide a structured approach to component design, state management, and data flow in Angular projects. The design allows the component to be reusable, maintainable, and performant within larger SPAs.

Practical Example

typescript
TYPESCRIPT Code
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-counter',
template: `     <div class="counter">       <h3>Count: {{ count }}</h3>       <button (click)="increment()">+</button>       <button (click)="decrement()">-</button>     </div>
`,
styles: [`     .counter {
display: flex;
gap: 10px;
align-items: center;
justify-content: center;
}
`]
})
export class CounterComponent {
@Input() count: number = 0;
@Output() countChange = new EventEmitter<number>();

increment() {
this.count++;
this.countChange.emit(this.count);
}

decrement() {
this.count--;
this.countChange.emit(this.count);
}
}

Advanced Angular Implementation

typescript
TYPESCRIPT Code
import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-smart-counter',
template: `     <div class="smart-counter">       <h3>Smart Counter: {{ value }}</h3>       <button (click)="increase()">+</button>       <button (click)="decrease()">-</button>     </div>
`,
styles: [`     .smart-counter {
background-color: #eef2f7;
padding: 16px;
border-radius: 12px;
text-align: center;
}
`]
})
export class SmartCounterComponent implements OnInit, OnChanges {
@Input() value: number = 0;
@Output() valueChange = new EventEmitter<number>();

ngOnInit() {
console.log('SmartCounter initialized with value:', this.value);
}

ngOnChanges(changes: SimpleChanges) {
if (changes['value']) {
console.log('Value changed:', changes['value'].currentValue);
}
}

increase() {
this.value++;
this.valueChange.emit(this.value);
}

decrease() {
this.value--;
this.valueChange.emit(this.value);
}
}

The advanced SmartCounterComponent example demonstrates using @Input, @Output, and lifecycle hooks OnInit and OnChanges to handle external data reactively and manage internal state. Initialization and change detection are logged for debugging, while EventEmitter allows updates to propagate to the parent component.
This example illustrates how decorators help structure high-performance, reusable Angular components while avoiding common pitfalls like prop drilling and unnecessary re-renders. Combining lifecycle hooks, decorators, and events allows developers to control component behavior and data flow precisely, improving maintainability and performance in enterprise applications.

Best practices for Angular decorators include using @Input for necessary data only, and @Output for clearly defined events. Avoid direct state mutation and excessive prop drilling. Use ChangeDetectionStrategy.OnPush to optimize performance and minimize unnecessary re-renders. Debugging can be improved with Angular DevTools by tracking component lifecycle and event emissions. For security, prevent injection of untrusted data and enable strict template type checking. Proper use of decorators ensures scalable, maintainable, and high-performing Angular applications.

📊 Comprehensive Reference

Angular Element/Method Description Syntax Example Notes
@Component Defines a component @Component({...}) @Component({ selector:'app-demo', template:'...' }) Most commonly used decorator
@Directive Custom directive @Directive({...}) @Directive({ selector:'[highlight]' }) Extend DOM behavior
@Pipe Data transformation @Pipe({...}) @Pipe({name:'capitalize'}) Transform template data
@NgModule Module definition @NgModule({...}) @NgModule({ declarations:[], imports:[] }) Organizes components and directives
@Injectable Service injection @Injectable({...}) @Injectable({ providedIn:'root' }) Dependency injection
@Input Input property @Input() prop:type @Input() title:string Parent-to-child data binding
@Output Output event @Output() event=new EventEmitter() @Output() clicked=new EventEmitter() Child-to-parent communication
@HostListener Listen to DOM events @HostListener('click') handler(){} @HostListener('window:scroll') onScroll() Bind host events
@ViewChild Access template child component @ViewChild(ChildComponent) child!:ChildComponent Manipulate child component
@ContentChild Access projected content @ContentChild(TemplateRef) tpl!:TemplateRef Manipulate projected template
@HostBinding Bind host property @HostBinding('class.active') isActive=true Dynamically bind host attributes

📊 Complete Angular Properties Reference

Property Values Default Description Angular Support
selector string none Component selector All versions
template string none Component template 2+
styles array string[] none Component CSS
providers array [] Dependency providers 2+
inputs array [] Input properties 4+
outputs array [] Output events 4+
animations array [] Component animations 4+
changeDetection string 'Default' Change detection strategy 5+
encapsulation string 'Emulated' CSS encapsulation 2+
standalone boolean false Standalone component 14+
imports array [] Imported modules 14+
schemas array [] Allow custom elements 9+

In summary, mastering Angular decorators equips developers to build maintainable, high-performance, and reusable components. Understanding decorators enables effective state management, controlled data flow, and precise lifecycle handling. Next steps include exploring dependency injection, lifecycle hooks, change detection strategies, and RxJS for asynchronous data streams. Applying these techniques in real projects, along with performance optimization and debugging tools, will elevate Angular development proficiency to an advanced, production-ready level.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

3
Questions
🎯
70%
To Pass
♾️
Time
🔄
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top