Web
Analytics
angular life cycle hooks - Tutorial

For Consultation : +91 9887575540

Stay Connected :

Lifecycle hooks are the way Angular allows you to add code that works before or after each step of the routing life cycle or components. List of Angular Hooks offers are:

  • OnInit
  • OnDestroy
  • DoCheck
  • OnChanges
  • AfterContentInit
  • AfterContentChecked
  • AfterViewInit
  • AfterViewChecked
  1. declare that your directive or component class implements the interface and then
  2. . declare that your directive or component class implements the interface and then





OnInit and OnDestroy

The OnInit hook is called when your directive properties have been initialized, and before any of the child directive properties are initialized. Similarly, the OnDestroy hook is called when the directive instance is destroyed. This is typically used if we need to do some cleanup every time our directive is destroyed. In order to illustrate let’s write a component that implements both OnInit and OnDestroy: code/advanced-components/src/app/lifecycle/on-init/on-init.component.ts

The ngOnInit method of a component is called directly after the constructor and after the ngOnChange is triggered for the first time. It is the perfect place for initialisation work.

Step1: Create new component: app-angularlifecyclehooks1

Step2: Code for app-angularlifecyclehooks1

HTML

Step 3: Add reference of newly created component into app.component and write following code.





ngOnChanges:

The ngOnChanges will be called first when the value of a bound property changes. It executes, every time the value of an input property changes. It will receive a changes map, containing the current and previous values of the binding, wrapped in a SimpleChange.

{“brand”:{“previousValue“:””,”currentValue“:”BMW”}}

In the case above, one change to the input property brand is reported. The value of this property has been changed from an empty string to the string “BMW”.

ngOnChanges

The ngOnChanges hook, with it’s SimpleChanges object, is a little different. Here’s how you would implement it. Let’s say we have a component used like this:

Example

App.component.html

App.Component.ts

Ngonchange.component.ts

 






Select your currency