问题描述
我使用NGXS作为存储机制。在商店中,有一个条件列表,这些条件通过UI上的RuleEngineAddViewStepperConditionComponent
显示在*ngFor
中。因此,每个条件都有自己的RuleEngineAddViewStepperConditionListCardComponent
。
每个条件都包含诸如Selecttargettype之类的设置。这些设置每个都在一个额外的组件中实现,例如在RuleEngineAddViewStepperConditionListCardSelecttargettypeComponent
中。如果用户现在更改设置,则此设置将更改并通过分派保存在商店中。通过更改StoreModel,* ngFor再次由Observable触发,后者也触发ngOnInit
,这会导致带有以下错误的循环。如何更改设置,以便更新列表,但不会引发错误?
RuleEngineAddViewStepperConditionComponent
<div *ngFor="let condition of (conditions$ | async)">
<app-rule-engine-add-view-stepper-condition-list-card [conditionId]="condition.conditionId">
</app-rule-engine-add-view-stepper-condition-list-card>
</div>
export class RuleEngineAddViewStepperConditionComponent {
...
@Select(RuleEnginestate.getConditions)
public conditions$: Observable<RuleCondition[]>;
...
}
RuleEngineAddViewStepperConditionListCardComponent
<app-rule-engine-add-view-stepper-condition-list-card-select-target-type [conditionId]="conditionId">
</app-rule-engine-add-view-stepper-condition-list-card-select-target-type>
RuleEngineAddViewStepperConditionListCardSelecttargettypeComponent
<mat-form-field [formGroup]="form">
...
</mat-form-field>
export class RuleEngineAddViewStepperConditionListCardSelecttargettypeComponent implements OnInit {
...
public ngOnInit(): void {
this.ruleId = this.store.selectSnapshot(RuleEnginestate.getSelectedRuleId);
}
private onFormChanges(): void {
this.form.valueChanges.subscribe(val => {
const targettype: RuleConditiontargettype = val.targettype;
if (targettype) {
this.store.dispatch(new RuleEngineConditionAddtargettypeAction(this.ruleId,this.conditionId,targettype));
}
});
}
...
}
解决方法
我找到了一个有用的解决方案。我使用TrackBy阻止呈现完整列表,现在我仅呈现新添加的元素。
https://dzone.com/articles/how-to-use-trackby-with-ngfor-in-angular-8