What are Angular decorators and what are the most important ones?
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.
// 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 { }
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
}
export class DataService {
constructor(
@Inject(API_URL) private apiUrl: string, // inject by token
@Optional() private logger?: LogService, // optional dependency
) {}
}
// inject() function replaces constructor parameter decorators
export class DataService {
private apiUrl = inject(API_URL);
private logger = inject(LogService, { optional: true });
}
All Comments