Angular
Building UI Functionality with Angular Components
  •  

Component Lifecycle Hooks

PRO

In AngularJS, we had access to an attribute directive (ng-init) where we could run a method from our \$scope on the page initialization procedure. This Lifecycle Hook has now been expanded in Angular to support a variety of events that we can target. Currently, there are now eight supported lifecycle hooks. The most commonly used hooks are:

  • ngOnChanges - This is called when data changes in your application that affects this component specifically
  • ngOnInit - This is called when the component initializes for the first time (i.e. it's only called once)
  • ngOnDestroy - This is called when the component is about to be destroyed (i.e. removed from the page)

Each of these hooks can be useful for executing functions during specific events triggered by a component during its instantiation, modification, and existence. Attaching a lifecycle hook is quite simple and only requires three steps:

// 1. Import our lifecycle hook
import { OnInit, OnDestroy } from '@angular/core';

@Directive({ selector: '[myDirective]' })
export class MyDirective implements OnInit, OnDestroy {
  // 2. Declare the interface on our class above

  constructor() {}

  // 3. Implement the lifecycle hooks

  ngOnInit() {
    console.log('onInit');
  }

  ngOnDestroy() {
    console.log('onDestroy');
  }
}

The Angular Team has created a great documentation page describing more about when it is best to use Lifecycle Hooks and how best to integrate them within an application.

In the next chapter, we'll dig into a more advanced (and very common) usage of components: nesting them.

 

I finished! On to the next chapter