英文:
At which point does ngOnChanges() gets fired
问题
The exact time when the ngOnChanges() method is called:
- 当值发生改变时
- 当引用发生改变时
英文:
What is the exact time when the ngOnChanges() method is called?
- When value changes
- When reference changes
答案1
得分: 2
Angular在检测组件的@Input属性发生变化时,会触发ngOnChanges方法。该方法接收一个SimpleChanges对象,其中包含当前和先前的属性值。您可以迭代已更改的属性并根据自己的逻辑使用它们。
您的组件的每个@Input属性都会得到一个SimpleChange对象(如果属性值发生更改)。
SimpleChanges是一个包含所有这些SimpleChange对象实例的对象。您可以通过使用@Input属性的名称作为键来访问它们。
例如,如果两个@Input属性message1和message2发生了变化,那么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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论