Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Adam Biro
Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Blog Post

Life Cycle Hooks in Angular 10

June 20, 2022 Angular, IT, Programming
Life Cycle Hooks in Angular 10

In the last episode of this series, I wrote about view files of Angular components. In the current post, I want to go through the Life Cycle Hooks in Angular.

The Life Cycle Hook term refers to several stages of a component instantiation process. When Angular instantiates a component class and renders a component with its child views then the component instance goes through a certain Life Cycle. In your code, you can access these stages with different methods.

What is the life cycle hook for?

As I mentioned above we can use Life Cycle Hook methods. They help us to tap into key events in the Life Cycle of a component or directive. Through these methods, we can detect changes, we can respond to updates, and clean up before deletion. It is worth mentioning that even if you do not have to import them, it is a good practice to do so.

Which are the Life Cycle Hooks Functions?

  1. ngOnChanges
    • When the content of the input field changes, this method will run.
  2. ngOnInit
    • Called once when the component is initialized but before any DOM changes. However after when the constructor is initiated.
  3. ngDoCheck
    • It runs when changes happen in the template of the component or in the component. Eg. Manually informing Angular about some specific change.
  4. ngAfterContentInit
    • Called after ngContent initialization. Not the view of the component itself instead of the view of the parent component especially when we add template code though the ngContent from the parent to the child.
  5. ngAfterContentChecked
    • It executes whenever change detection checked this content where projected into our component
  6. ngAfterViewInit
    • It will run after the view of our component already initialized. When Angular renders the view of our component.
  7. ngAfterViewChecked
    • It runs whenever our view has been checked. Once we are sure that either all changes which had to be done were displayed in the view or no changes were detected by Angular
  8. ngOnDestroy
    • If you place ng-if on a component and when it will be set to false and therefore it will be removed from the DOM then ngOnDestroy is called.
    • This is a great place to do some cleanup work because it is running right before the object itself is destroyed by Angular.

Conclusion

Life Cycle Hooks are functions to modify and change the behavior of the components and directives. It gives us the tool in the Angular context to affect the behavior of certain aspects of our components.

Episodes

Taggs:
Write a comment