Overblog Tous les blogs Top blogs Technologie & Science Tous les blogs Technologie & Science
Editer l'article Suivre ce blog Administration + Créer mon blog
MENU
Publicité

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 ngOnChanges method is called. You can say ngOnChanges is a lifecycle hook. And It’s called when any data-bound property of directive change. The ngOnChanges lifecycle-hook is called when the angular ChangeDetection directs an @Input change in your component.

 

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;
  }
}

ngOnChanges() will fire before ngOnInit() and every time parentDatais updated from its parent component.

ngOnChanges() takes a changes argument of type SimpleChanges.

changeFromChild() won't call ngOnChanges()

changeFromParent() will call ngOnChanges()

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

The SimpleChanges instance looks like this...

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

 Read More

 

Publicité
Tag(s) : #angular
Partager cet article
Repost0
Pour être informé des derniers articles, inscrivez vous :