In Angular, a decorator is a special kind of declaration that attaches metadata to a class, method, property, or parameter. Angular uses decorators extensively to understand how different pieces of your application should work.
They are just functions prefixed with @
that tell Angular how to treat a class or element.
Common Angular Decorators
- Class Decorators → used with classes
@Component()
→ defines a component@Directive()
→ defines a directive@Pipe()
→ defines a pipe@Injectable()
→ marks a class as available for Dependency Injection@NgModule()
→ defines an Angular module
@Component({ selector: 'app-hello', template: `<h1>Hello Angular!</h1>` }) export class HelloComponent {}
- Property Decorators → used with properties inside classes
@Input()
→ allows a parent component to pass data into a child component@Output()
→ allows a child component to emit events to a parent@ViewChild()
/@ViewChildren()
→ access child elements/components in the template@ContentChild()
/@ContentChildren()
→ access projected content
export class ChildComponent { @Input() title!: string; @Output() clicked = new EventEmitter<string>(); }
- Parameter Decorators → used with constructor parameters
@Inject()
→ specifies a custom provider to inject@Optional()
→ makes dependency optional@Self()
/@SkipSelf()
/@Host()
→ control dependency injection resolution
constructor(@Optional() private logger?: LoggerService) {}
- Method Decorators → less common, used for lifecycle hooks or special behaviors.
Why Decorators Are Important in Angular
- They configure classes without changing their logic.
- They tell Angular how to create, inject, and use the class or property.
- They enable Dependency Injection (DI), Component Templates, Change Detection, etc.