In Angular, decorators play a crucial role in defining the behavior, structure, and metadata of various building blocks, such as components, directives, modules, and services. Here are some of the most important decorators in Angular:
1. @Component
- Purpose: Defines a component, which is the basic building block of an Angular application.
- Usage: Specifies metadata like the template, styles, and selector for a component.
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css'],
})
export class HelloComponent {}
2. @NgModule
- Purpose: Defines an Angular module, which is used to group related components, directives, pipes, and services.
- Usage: Specifies declarations, imports, providers, and bootstrap configurations.
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
3. @Directive
- Purpose: Defines a custom directive to extend HTML functionality.
- Usage: Creates attribute or structural directives.
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
4. @Injectable
- Purpose: Marks a class as a service that can be injected into other classes.
- Usage: Used in Angular’s dependency injection system.
@Injectable({
providedIn: 'root', // Available at the root level
})
export class DataService {
getData() {
return ['Item 1', 'Item 2'];
}
}
5. @Input
- Purpose: Binds a property in a child component to a value passed from the parent component.
- Usage: Used for parent-to-child data binding.
@Component({
selector: 'app-child',
template: '{{ message }}
',
})
export class ChildComponent {
@Input() message: string; // Message passed from parent
}
6. @Output
- Purpose: Emits an event from a child component to notify the parent component.
- Usage: Used for child-to-parent communication.
@Component({
selector: 'app-child',
template: '<button (click)="sendMessage()">Send</button>',
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from Child');
}
}
7. @HostListener
- Purpose: Listens to DOM events and triggers a method.
- Usage: Allows handling events directly within the directive or component.
@Directive({
selector: '[appClickTracker]',
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
handleClick(event: Event) {
console.log('Element clicked:', event);
}
}
8. @HostBinding
- Purpose: Binds a DOM property or attribute to a property in the directive or component.
- Usage: Dynamically update the host element’s properties or attributes.
@Directive({
selector: '[appBackground]',
})
export class BackgroundDirective {
@HostBinding('style.backgroundColor') bgColor: string;
constructor() {
this.bgColor = 'lightblue';
}
}
9. @Pipe
- Purpose: Marks a class as a custom pipe that transforms data in templates.
- Usage: Used for custom data transformations.
@Pipe({
name: 'capitalize',
})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
10. @ViewChild
- Purpose: Access a child component, directive, or DOM element from the parent component.
- Usage: Used to manipulate child elements programmatically.
@Component({
selector: 'app-parent',
template: '<app-child #childComp></app-child>',
})
export class ParentComponent {
@ViewChild('childComp') child: ChildComponent;
ngAfterViewInit() {
console.log(this.child);
}
}
11. @ViewChildren
- Purpose: Access multiple child elements or components from the parent component.
- Usage: Used to work with a collection of children.
@Component({
selector: 'app-parent',
template: '<div *ngFor="let item of items" #div>{{ item }}</div>',
})
export class ParentComponent {
@ViewChildren('div') divs: QueryList<ElementRef>;
ngAfterViewInit() {
this.divs.forEach(div => console.log(div.nativeElement.textContent));
}
}
12. @ContentChild
- Purpose: Access a single projected content element from a parent component.
- Usage: Used in components with
<ng-content>
slots.
@Component({
selector: 'app-wrapper',
template: '',
})
export class WrapperComponent {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
13. @ContentChildren
- Purpose: Access multiple projected content elements from a parent component.
- Usage: Used for querying multiple
<ng-content>
elements.
@Component({
selector: 'app-wrapper',
template: '',
})
export class WrapperComponent {
@ContentChildren('item') items: QueryList;
ngAfterContentInit() {
this.items.forEach(item => console.log(item.nativeElement.textContent));
}
}
These decorators form the foundation of Angular development, enabling you to define structure, behavior, and communication between different parts of your application.