-2

What is the exact time when the ngOnChanges() method is called?

  1. When value changes
  2. When reference changes
maxxi
  • 197
  • 4
  • 11
  • It fires when the reference changes. This question will help clarify further for you on when ngOnChanges is run. https://stackoverflow.com/questions/34796901/angular2-change-detection-ngonchanges-not-firing-for-nested-object?rq=2 – Passersby Apr 11 '23 at 04:14

1 Answers1

2

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.

CodeWarrior
  • 5,026
  • 6
  • 30
  • 46