What is the exact time when the ngOnChanges() method is called?
- When value changes
- When reference changes
What is the exact time when the ngOnChanges() method is called?
Angular fires ngOnChanges
when it detects changes to the @Input
properties of a Component. The method receives a SimpeChanges
object, which contains the current and previous property values. You can iterate over the changed properties and use them according to your logic.
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
@Input() prop: number = 0;
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}
Every @Input
property of your component gets a SimpleChange
object (if the Property value changed)
SimpleChanges
is an object that contains all the instance of these SimpleChange
objects. You can access them by using the name of the @Input
property as the key.
For example, if two @Input
properties message1
& message2
were changed, then the SimpleChanges
object will look like this:
{
"message1":
{ "previousValue":"oldvalue",
"currentValue":"newvalue",
"firstChange":false
},
"message2":
{ "previousValue":"oldvalue",
"currentValue":"newvalue",
"firstChange":false
}
}
Hope this helps.