What are decorators in Angular? What are the different types?
Decorators are special TypeScript functions (prefixed with @) that attach metadata to classes, properties, methods, or parameters. Angular uses them everywhere to wire up DI and the framework.
Class decorators —
@Component,@NgModule,@Directive,@Pipe,@Injectable; mark the class's role.Property decorators —
@Input(),@Output(),@ViewChild(),@ContentChild(); bind class fields to the template/DOM.Method decorators —
@HostListener(),@HostBinding(); tie methods/properties to host element events and attributes.Parameter decorators —
@Inject(),@Optional(),@Self(),@SkipSelf(),@Host(); control DI behavior on constructor params.Compile-time — the Angular compiler reads decorators to generate factory code.
// All four decorator types in one example
import { Component, Input, Output, EventEmitter, HostListener, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({ // CLASS decorator
selector: 'app-counter',
standalone: true,
template: `<button (click)="bump()">{{ count }}</button>`,
})
export class CounterComponent {
@Input() start = 0; // PROPERTY decorator
@Output() changed = new EventEmitter<number>(); // PROPERTY decorator
count = this.start;
constructor(@Inject(DOCUMENT) private doc: Document) {} // PARAMETER decorator
@HostListener('window:keydown.escape') // METHOD decorator
reset() { this.count = 0; }
bump() { this.changed.emit(++this.count); }
}Demonstrates all four decorator categories on a single component: @Component (class) wires the template and selector, @Input/@Output (property) declare the parent contract, @HostListener (method) binds a DOM event to a class method, and @Inject (parameter) overrides DI resolution. Each decorator attaches metadata that Angular reads at compile time via reflect-metadata.
Bucket them: class (@Component, @Injectable), property (@Input, @Output), method (@HostListener), parameter (@Inject). All ride on reflect-metadata for DI.