What are Angular Decorators and how do they work?

What are Angular Decorators and how do they work?

What are Angular Decorators and how do they work?

Question

What are Angular decorators and what are the most important ones?

Answer

Decorators are a TypeScript feature (also a stage 3 JS proposal) that attach metadata to a class, method, property, or parameter. Angular uses decorators extensively to configure how its classes behave.

Class Decorators

// Marks a class as an Angular component
@Component({
  selector:    'app-root',
  standalone:  true,
  templateUrl: './app.component.html',
})
export class AppComponent { }

// Marks a class as injectable (a service)
@Injectable({ providedIn: 'root' })
export class UserService { }

// Marks a class as a custom pipe
@Pipe({ name: 'truncate', standalone: true })
export class TruncatePipe implements PipeTransform { }

// Marks a class as a directive
@Directive({ selector: '[appHighlight]', standalone: true })
export class HighlightDirective { }

Property Decorators

export class ProductCardComponent {
  @Input()  product!: Product;        // receive data from parent
  @Output() addToCart = new EventEmitter<Product>(); // emit to parent

  @ViewChild('container')  container!: ElementRef;  // access DOM
  @ContentChild('header')  header!:    ElementRef;  // access projected content
}

Parameter Decorators

export class DataService {
  constructor(
    @Inject(API_URL) private apiUrl: string,  // inject by token
    @Optional() private logger?: LogService,   // optional dependency
  ) {}
}

Modern Alternative — inject()

// inject() function replaces constructor parameter decorators
export class DataService {
  private apiUrl = inject(API_URL);
  private logger = inject(LogService, { optional: true });
}
All Comments