ngonchanges example angular 8

You are currently viewing ngonchanges example angular 8

ngOnChanges is a callback method. It is used to detect the changes in input property in angular programming. ngOnChanges is called immediately data-bound properties through the default change detector. When the default change detector has checked the data-bound properties then the ngOnChange method is called. You can say ngOnChange is a lifecycle hook. And It’s called when any data-bound property of directive change. The ngOnChange lifecycle-hook is called when the angular ChangeDetection directs an @Input change in your component.

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

Methods of ngOnChanges

ngOnChanges(changes: SimpleChanges): void

changes is parameters. and SimpleChanges is the properties of change. And the void is returned.

Examples:

The following example shows how a component can implement this interface to define an on-changes handler for an input property.

The following example shows how a component is implemented to define a ngOnChange for an input property.

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
  // TODO(issue/24571): remove '!'.
  @Input()
  prop !: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}

To handle changes, a directive must implement the ngOnChange method to receive notifications when the value of an input property changes, as shown in the following example.

import { Directive, ElementRef, Attribute, Input,
 SimpleChange } from "@angular/core";
@Directive({
 selector: "[pa-attr]"
})
export class PaAttrDirective {
 constructor(private element: ElementRef) {}
 @Input("pa-attr")
 bgClass: string;
 ngOnChanges(changes: {[property: string]: SimpleChange }) {
 let change = changes["bgClass"];
 let classList = this.element.nativeElement.classList;
if (!change.isFirstChange() && classList.contains(change.previousValue)) {
 classList.remove(change.previousValue);
 }
 if (!classList.contains(change.currentValue)) {
 classList.add(change.currentValue);
 }
 }
}

The ngOnChange method is called once before the ngOnInit method and then called again each time there are changes to any of a directive’s input properties. The easiest way to understand the way that changes are presented to the ngOnChange method is to serialize the object. The ngOnChange parameter is an object whose property names refer to each changed input property and whose values are SimpleChange objects, which are defined in the @angular/core module. TypeScript represents this data structure as follows:

...
ngOnChanges(changes: {[property: string]: SimpleChange }) {
...

We two components parent component and child component. We will pass some data from the parent component to the child component. We need to have a @input decorator in the child component. We will pass the value from the parent component. ngOnChange of the child component will be called every time when we change parent component value.



Some code to clarify:

parent component :

import { Component, OnInit } from '@angular/core';
 
@Component({
 selector: 'my-app',
 template: `<strong>Component used with input:</strong>
 <hello [sometingForChild]="inputFromParent"></hello>`
})
 
export class AppComponent implements OnInit {
 inputFromParent;
 
 ngOnInit(){
 this.inputFromParent = 'first call'; 
 // First change. ngOnChanges of HelloComponent(child) will be called at   
 // first here.
 
 setTimeout( ()=>{ this.inputFromParent = 'second call'}, 1500 );
 // Second change. ngOnChanges of HelloComponent will be called second    
 // time here.
 }
}

child component:

import { Component, Input, SimpleChanges } from '@angular/core';
 
@Component({
 selector: 'hello',
 template: `{{whatIsInInput}} {{whatWasInInput}}`
})
 
export class HelloComponent {
 @Input() sometingForChild: string;
 
 whatIsInInput : string;
 whatWasInInput : string;
 
 ngOnChanges(changes: SimpleChanges) {
   this.whatIsInInput = changes.sometingForChild.currentValue;
   this.whatWasInInput = changes.sometingForChild.previousValue;
 }
}

Output:

first call

second call first call // after 15 seconds
ngOnChanges

Visit the angular tutorial list. And make strong your angular concept. click here. wuschools.com is always written about agular concept for the angular lover. Ang write about how angular make your life easy if you are a web site developer.

More Examples:

child.component.ts

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

@Component({
  selector: 'app-child',
  template: `
    <a (click)="changeFromChild()">Change from child</a>
    <br/>
    {{parentData}}
  `	
})
export class ChildComponent implements OnInit {
  @Input() parentData: any;
  constructor() {
  }

  ngOnInit() {
  }

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

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

parent.component.ts

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

@Component({
  selector: 'app-parent',
  template: `
    <a (click)="changeFromParent()">Change from parent</a>
    <br/>
    <app-child [parentData]=data></app-child>
  `
})
export class ParentComponent implements OnInit {
  data = 0
  constructor() {
  }

  ngOnInit() {
  }

  changeFromParent(){
    this.data += 1;
  }
}
import { Directive, ElementRef, Attribute, Input,
 SimpleChange } from "@angular/core";
@Directive({
 selector: "[pa-attr]"
})
export class PaAttrDirective {
 constructor(private element: ElementRef) {}
 @Input("pa-attr")
 bgClass: string;
 ngOnChanges(changes: {[property: string]: SimpleChange }) {
 let change = changes["bgClass"];
 let classList = this.element.nativeElement.classList;
if (!change.isFirstChange() && classList.contains(change.previousValue)) {
 classList.remove(change.previousValue);
 }
 if (!classList.contains(change.currentValue)) {
 classList.add(change.currentValue);
 }
 }
}

The ngOnChange method is called once before the ngOnInit method and then called again each time there are changes to any of a directive’s input properties. And ngOnChanges method called every time when the value will be change. The ngOnChange parameter is an object whose property names refer to each changed input property and whose values are SimpleChange objects, which are defined in the @angular/core module. In the above I have explain already ngOnChange method is called when the value is changed. ngOnChange is the life cycle hook.

ngonchanges example angular 7

ngonchanges example angular 6

ngonchanges example angular 5

ngonchanges example angular 4

If you want to read more: Then visit the official document. Angular.



This Post Has 4 Comments

Leave a Reply