[英]How can I trigger ngOnChanges only after every input values has been set in ngOnInit
How can I trigger ngOnChanges only after every input values has been set in ngOnInit. 如何在ngOnInit中设置每个输入值后才能触发ngOnChanges。 My code -->
我的代码 - >
`ngOnInit() {
this.multiSelectorData.forEach(item=>{
this.allItems.push(item.data);
});
}
ngOnChanges(changes: SimpleChanges) {
if(changes['dataReady'] && changes['dataReady'].currentValue) {
console.log(this.allItems);
}`
I wont get the array I initialized in ngonit in ngonchanges because ngonchanges is called before ngonit, how can i check if all are initialized before checking ngonchanges? 因为在ngonit之前调用了ngonchange,所以我不会得到我在ngonit中初始化的数组,如何在检查ngonchanges之前检查是否所有都被初始化了?
One method I have found that works is based on the fact that the input values all have a previous value property. 我发现一种方法是基于输入值都具有先前值属性的事实。 If the input has not previously been set then that value will be
CD_INIT_VALUE
(as a string). 如果先前未设置输入,则该值将为
CD_INIT_VALUE
(作为字符串)。 So you can make a condition that your block of code in ngOnChanges
should only run if the previous value is not CD_INIT_VALUE
. 因此,您可以设置一个条件,即只有在前一个值不是
CD_INIT_VALUE
, ngOnChanges
应运行ngOnChanges
的代码块。 Here's an example for your case where you're testing ALL the input values: 以下是您测试所有输入值的示例:
ngOnChanges(changes: SimpleChanges) {
let initialized: boolean = true;
for (let prop in changes) {
if (changes[prop].previousValue.toString() === 'CD_INIT_VALUE') {
initialized = false;
//we can break here since if any item is not initialized
//we will say the inputs are NOT initialized
break;
}
}
if (initialized) {
//code you want to execute
}
}
There are probably more elegant solutions but I've found this works. 可能有更优雅的解决方案,但我发现这是有效的。 This is probably too late to help you but may help others as when I googled this I found this question.
这可能为时已晚,无法帮助你,但可能会帮助别人,因为当我用Google搜索时,我发现了这个问题。 The solution was something I figured out from debugging.
解决方案是我从调试中发现的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.