我遇到了一个谜团。我在一个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将不会只被调用它的ngOnChanges和(descriptor,rc,item)的新值。对于所有其他的'vi-rule-contract‘,将调用ngOnInit,但不会调用ngOnChanges。所以我的问题是:
有没有这样一种情况,一个组件上的ngOnInit永远不会只调用它的ngOnChanges?
PS Angular 6.1.10
发布于 2019-03-15 04:26:23
问题是,你有一个定义列表的函数,这意味着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何时更改,但您可能会在可观察的订阅中或其他什么地方执行此操作
https://stackoverflow.com/questions/55171323
复制相似问题