AppDividend
Latest Code Tutorials

Angular ngOnChanges Lifecycle Method Example

0

Angular ngOnChanges is a lifecycle hook that is called when any data-bound property of a directive changes. To respond to changes to the @Input() variables, use the ngOnChanges() lifecycle hook. The ngOnChanges() takes the changes argument of type SimpleChanges.

Angular ngOnChanges

The ngOnChanges() is an inbuilt Angular callback method that is invoked immediately after the default change detector has checked data-bound properties if at least one has changed. Before the view and content, children are checked.

interface OnChanges {
  ngOnChanges(changes: SimpleChanges): void
}

Let’s understand this by an example.

Angular bydefault comes with AppComponent. It will act as a parent component.

Let’s create one more component called ChildComponent.

So, now we have two components.

  1. AppComponent: Parent Component
  2. ChildComponent: Child Component

We define a property inside the Parent component and pass that property to Child component, and it will accept that property using @Input directive.

We modify the value of the property from the Parent and Child component.

Write the following code inside the app.component.ts file.

// app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  data = 0;
  constructor() {
  }

  ngOnInit(): void {
  }

  changeFromParent(): void {
    this.data += 1;
  }
}

We are defining a class property called data whose initial value is 0.

Then we have defined a function called changeFromParent(), which is called when the button is clicked.

After the button is clicked, the value of the property will be modified, and it will add +1.

Write the following code inside the app.component.html file.

<!-- app.component.html -->

<div class="container">
  <div class="row">
    <div class="col-md-4">
      <a (click)="changeFromParent()" class="btn btn-success">Change from parent</a>
    </div>
    <div class="col-md-8">
      <app-child [parentData]=data></app-child>
    </div>
  </div>
</div>

We have used bootstrap 4 for styling our components.

In this code, we have defined a click event, and if it is fired, then the data property will be incremented by one, and it is defined inside the parent component.

We have also defined a Child component that accepts the parentData as input data from the Parent component.

So, write the following code inside the child.component.ts file.

// child.component.ts

import { Component, OnInit, Input, SimpleChanges, OnChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {

  @Input() parentData: any;

  constructor() { }

  ngOnInit(): void {
  }

  changeFromChild(): void {
    this.parentData -= 1;
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log(changes);
  }

}

You can see that we have defined @Input property that indicates we have input data from the parent component.

Then we have defined two methods.

  1. changeFromChild()
  2. ngOnChanges()

The changeFromChild() is a method that will be called when we are clicking a link from the child component. Just like we have defined inside the app.component.ts file.

The ngOnChanges() method will be invoked when we are changing the data property from the parent component. It will log the changes object whose format is following.

  1. previousValue
  2. currentValue
  3. firstChange (true the first time ngOnChanges is called)

The SimpleChanges instance looks like the following.

class SimpleChange {
  constructor(previousValue: any, currentValue: any, firstChange: boolean)
  previousValue: any
  currentValue: any
  firstChange: boolean
  isFirstChange(): boolean
}

Every time ngOnChanges() is called, the SimpleChanges instance captures the parentData.

The changeFromChild() won’t call ngOnChanges().

The changeFromParent() will call ngOnChanges().

When ngOnChanges() is called, this example simply logs the SimpleChanges instance.

Output

Angular ngOnChanges

If you press the Change from parent link, it will increment the data by 1, and also it will log the changes object.

If you press the Change from child link, it will decrement the data by 1.

The SimpleChanges instance looks like the following.

Conclusion

Use ngOnChanges hook whenever you want to detect changes from a variable decorated by @Input.

Remember that only changes from the parent component will trigger the ngOnChanges() function.

Also, remember that changes from the parent still update the child value even without implementing ngOnChanges.

The ngOnChanges simply adds the benefit of tracking those changes with the previous and current value.

That is it for Angular ngOnChanges().

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.