Sunday, November 18, 2018

ngOnChanges lifecycle hook

The ngOnChanges lifecycle hook is executed when any of the components data-bound input properties are changed. Let us see how this works with a simple example.

We have a parent component which has a nested child component. The parent component has a property “message”, the component also has a button on click of which we change the text of the message property in the button’s click handler. We embed a child component and pass the message as an @Input property to the child component. When we click the button in the parent component the message property changes and hence the value passed in the @Input property will also change, this should trigger the ngOnChanges lifecycle hook in the child component.

Parent Component.
import { Component, OnInit  } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  message: string;
  constructor() { }
  ngOnInit() {
    this.message = 'Hello from Parent.'
  }
  clickHandler() {
    this.message = 'Update from Parent.';
  }
}

Parent component template
<div>
  <app-child [Message] = "message"></app-child>
  <input type="button" (click)='clickHandler()' value="Change Message">
</div>

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

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

  ngOnChanges(changes: SimpleChanges) {
    console.log('Triggering ngOnChanges');
    console.log(JSON.stringify(changes));
  }
}

Child component template
<p>
  Input Message: {{ Message }}
</p> 

Final output


Search Flipkart Products:
Flipkart.com

No comments: