ngOnChanges() 在哪个时刻被触发

huangapple go评论67阅读模式
英文:

At which point does ngOnChanges() gets fired

问题

The exact time when the ngOnChanges() method is called:

  1. 当值发生改变时
  2. 当引用发生改变时
英文:

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

  1. When value changes
  2. When reference changes

答案1

得分: 2

Angular在检测组件的@Input属性发生变化时,会触发ngOnChanges方法。该方法接收一个SimpleChanges对象,其中包含当前和先前的属性值。您可以迭代已更改的属性并根据自己的逻辑使用它们。

您的组件的每个@Input属性都会得到一个SimpleChange对象(如果属性值发生更改)。

SimpleChanges是一个包含所有这些SimpleChange对象实例的对象。您可以通过使用@Input属性的名称作为键来访问它们。

例如,如果两个@Input属性message1message2发生了变化,那么SimpleChanges对象将如下所示:

{
  "message1": 
   {  "previousValue":"oldvalue",
      "currentValue":"newvalue",
      "firstChange":false 
   },
  "message2": 
   {  "previousValue":"oldvalue",
      "currentValue":"newvalue",
      "firstChange":false
   }
}

希望这有所帮助。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月11日 12:10:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定