[英]Angular ngOnInit executed when the component is not present on the DOM
[英]Angular ngOnInit never executed when creating component inside ngFor
我遇到了一个谜。 我在这个示例中处于ngFor循环中:
<div *ngFor="let rc of sortedKeys(ruleImplementations)">
<vi-rule-contract [descriptor]="ruleDescriptors[rc]" [item]="action" [rc]="rc">
</vi-rule-contract>
</div>
仅对于这N个已创建的“ vi-rule-contract”组件(非常具体的一个)中的一个(非常具体的组件),ngOnInit不会仅使用其新的值(描述符,rc,item)调用其ngOnChanges。 对于所有其他'vi-rule-contract',将调用ngOnInit但从不ngOnChanges。 所以这是我的问题:
有没有一种情况,组件上的ngOnInit永远不会只被调用它的ngOnChanges?
PS Angular 6.1.10
问题是你有一个定义你的列表的函数,这意味着ngFor不断重新执行,这是非常糟糕的做法,angular正试图通过仅实例化组件一次但改变输入来节省你。
您在此处的修复是停止在模板中使用函数,并在需要时运行它。
<div *ngFor="let rc of sortedRuleImplementations">
<vi-rule-contract [descriptor]="ruleDescriptors[rc]" [item]="action" [rc]="rc">
</vi-rule-contract>
</div>
this.sortedRuleImplementations = this.sortedKeys(ruleImplementations);
当ruleImplementations发生更改时,我无法从您的代码中看出,但您可以在可观察的订阅或其他内容中执行此操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.