Introduction:
If you’re already familiar with components in Angular, you should know that it plays a significant role in the application’s architecture. A component is responsible for rendering a specific section of the application and includes its logic, markup, and styling. Knowing how to create and use components effectively is essential as an Angular developer. We previously discussed what Angular components are and how they work. This time, we’ll take a closer look at another crucial aspect of Angular components: its lifecycle hooks.
![lifecycle hooks in Angular](https://webdevtutos.com/wp-content/uploads/2023/11/Lifecycle-Hooks-in-Angular-1024x576.webp)
What are Lifecycle Hooks in Angular?
Every Angular component goes through various phases as it is being created, modified, and destroyed. Angular provides a way to tap into these phases via lifecycle hooks. A lifecycle hook is an interface having several methods that Angular calls at specific moments during a component’s creation, change detection, or destruction cycle. By implementing these methods in your component, you can add specific behaviors to your component during each life cycle phase.
Let’s explore the lifecycle hook methods in Angular components by dividing them into three categories: Component Creation, Input properties, and Component destruction.
ngOnInit
The `ngOnInit` method is executed after Angular has finished initializing and setting up the component. This lifecycle hook is mostly used for component initialization and retrieving data from a database. Here’s a code snippet:
export class AppComponent implements OnInit {
constructor() { }
ngOnInit() {
// place your initialization logic here
}
}
ngAfterContentInit
The `ngAfterContentInit` is another lifecycle hook method that Angular calls once it has projected external content into the component’s view, or after Angular has created the component’s children. This lifecycle hook is typically used when you need to perform some actions after Angular sets the component’s input properties. Here’s an example code snippet:
export class AppComponent implements AfterContentInit {
constructor() { }
ngAfterContentInit() {
// place your logic here that should run after content initialization
}
}
Remember, Angular only calls the `ngAfterContentInit` hook once, so it’s the perfect spot for initialization work that depends on bindings.
ngAfterContentChecked
The `ngAfterContentChecked` is another vital lifecycle hook that Angular calls after it checks the content projected into the component. This hook method is invoked every time Angular completes a check of the component’s content, including the initial check right after content initialization, and then subsequent checks after every change detection cycle. This lifecycle hook is generally used when you need to perform some actions after Angular completes checking the component’s content. Here’s an example code snippet:
export class AppComponent implements AfterContentChecked {
constructor() { }
ngAfterContentChecked() {
// place your logic here that should run after content check
}
}
Just like other lifecycle hooks, Angular calls the `ngAfterContentChecked` hook after both `ngAfterContentInit` and every `ngDoCheck`. It’s crucial to note that even though this hook is called frequently, it’s best to keep the operations inside this method as lightweight as possible to maintain application performance.
ngAfterViewInit
`ngAfterViewInit` is another integral lifecycle hook that Angular calls after it initializes the view and child views or the view that the directive is in. This hook method is particularly useful when you need to perform some actions after Angular initializes the component’s view(s). Just like `ngAfterContentInit`, Angular only calls the `ngAfterViewInit` hook once. Here’s an example code snippet:
export class AppComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit() {
// place your logic here that should run after view initialization
}
}
Remember, any attempt to change a data-bound property value within this lifecycle hook could lead to Angular throwing an error since the view has already been rendered. If you need to change the view, consider using `ngAfterViewChecked`.
ngOnChanges
The `ngOnChanges` hook is called whenever one or more data-bound input properties change. Use it to react to changes in your component’s input properties. Here’s how to use `ngOnChanges`:
export class AppComponent implements OnChanges {
@Input() data: any;
constructor() { }
ngOnChanges(changes: SimpleChanges) {
for (let propName in changes) {
let change = changes[propName];
let curVal = JSON.stringify(change.currentValue);
let prevVal = JSON.stringify(change.previousValue);
console.log(curVal);
console.log(prevVal);
}
}
}
ngDoCheck
The `ngDoCheck` hook runs whenever Angular’s change detector runs. It’s used to implement custom change detection. Here’s a code snippet:
export class AppComponent implements DoCheck {
constructor() { }
ngDoCheck() {
// custom change detection logic goes here
}
}
ngOnDestroy
Finally, the `ngOnDestroy` hook is called just before Angular destroys the directive or component. This is where you can clean up any subscriptions or connections to prevent memory leaks. Here’s an example:
export class AppComponent implements OnDestroy {
private subscription: Subscription;
constructor() { }
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Order of Angular lifecycle Hooks
In an Angular component’s lifecycle, the hooks are executed in a specific order. If all the hooks are present in a single component, they would be executed in the following order:
- ngOnChanges: This method is called after a bound input property changes.
- ngOnInit: This hook is called once the component’s input properties are checked for the first time.
- ngDoCheck: Called during every change detection run, immediately after ngOnChanges and ngOnInit.
- ngAfterContentInit: Called once after the first ngDoCheck.
- ngAfterContentChecked: Called after ngAfterContentInit and every subsequent ngDoCheck.
- ngAfterViewInit: Called once after the first ngAfterContentChecked.
- ngAfterViewChecked: Called after the ngAfterViewInit and every subsequent ngAfterContentChecked.
- ngOnDestroy: This method will be called just before Angular destroys the component.
These lifecycle hooks make it easier to manage the different phases of a component’s lifecycle, from initialization to cleanup.
Conclusion:
Understanding the different lifecycle hooks in Angular components is essential to creating high-quality, efficient, and bug-free applications. By tapping into these hooks, you can create unique and customized behaviors for your components. Proper utilization of lifecycle hooks can also help you optimize your components and ensure they run smoothly. By learning the best practices outlined in this post, you’re on your way to becoming a well-rounded Angular developer. happy coding.