Angular-lifecycle-hooks

Understanding Angular Lifecycle Hooks

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 Lifecycle Hooks

Types of Lifecycle Hooks

Angular provides several lifecycle hooks, including:

1. ngOnInit

Fires once after the component initializes. Commonly used for fetching initial data.

2. ngOnChanges

Runs when input properties change, helping track updates from parent components.

3. ngDoCheck

Detects changes manually, useful for custom change detection strategies.

4. ngAfterViewInit

Executes once the component’s view and child views are initialized.

Example of Lifecycle Hook Usage

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);
      }
    }