Saturday, December 1, 2018

ngOnChanges

A callback method that is invoked immediately after the default change detector has checked data-bound properties if at least one has changed, and before the view and content children are checked.

The ngOnChnages is a life cycle hook, which angular fires when it detects changes to data bound input property.
This method receives a SimpleChanges object,Which contains current and previous property values.

Called before ngOnInit() and whenever one or more data-bound input properties change.

The child Component decorates the property as a @Input annotation.
@Input() message: string;

And then parent passes the data to the child component using property binding as shown below
`

Whenever the parent changes the value of the message property, the Angular raises the OnChanges hook event in the child component, so that it can act upon it.

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

@Component({
  selector: 'greeter',
  inputs: ['name'],
  template: `
{{ greeting }}
`,
})
export class Greeter implements OnChanges {
  @Input() name: string;
  greeting: string;

  constructor() {}

  ngOnChanges(changes: SimpleChanges) {
if (changes['name']) {
  this.data = 'Hello ' + this.name;
}
  }
}

How does it work
The ngOnChanges() method takes an object that maps each changed property name to a SimpleChange object, which holds the current and previous property values. You can iterate over the changed properties and act upon it.

SimpleChange
SimpleChange is a simple class, which has three properties

PROPERTY NAME   DESCRIPTION
previousValue:any  Previous value of the input property.
currentValue:any New or current value of the input property.
FirstChange():boolean        Boolean value, which tells us whether it was the first time the change has taken place

No comments:

Followers

Link