Angular Lifecycle Hooks allow developers to tap into different phases of a component's life cycle, from creation to destruction. They provide greater control over component behavior and data flow.
Angular provides several lifecycle hooks, including:
ngOnInitFires once after the component initializes. Commonly used for fetching initial data.
ngOnChangesRuns when input properties change, helping track updates from parent components.
ngDoCheckDetects changes manually, useful for custom change detection strategies.
ngAfterViewInitExecutes once the component’s view and child views are initialized.
Here’s a basic example using ngOnInit to fetch data:
export class SampleComponent implements OnInit {
data: any;
constructor(private service: DataService) {}
ngOnInit() {
this.service.getData().subscribe(res => this.data = res);
}
}