我使用 *ngFor指令和新的@for块进行了不同级别的关闭. 我有一个父组件,它使用for循环创建多个子组件:
<app-active-problem class="panel" *ngFor="let activeProblem of summary.activeProblems" [activeProblem] = "activeProblem" (update)="updateActiveProblem($event);"></app-active-problem>
<!--
@for (activeProblem of summary.activeProblems; track $index) {
<app-active-problem class="panel" [activeProblem] = "activeProblem" (update)="updateActiveProblem($event);"></app-active-problem>
}-->
</ng-container>
在子组件中,我接受[active Problem]输入作为ProblemGroup| NarrativeProblem类. 为了有效区分两者并渲染视图. 我创建两个实例变量
problemGroup?: ProblemGroup;
narrativeProblem?: NarrativeProblem;
ngOnInit(): void {
if (this.activeProblem instanceof ProblemGroup) {
this.problemGroup = this.activeProblem as ProblemGroup;
} else {
this.narrativeProblem = this.activeProblem;
}
}
在同一个视图中,我有一个单击事件处理程序,可以切换问题组下的值(本质上是变异对象).
<input
clrCheckbox
type="checkbox"
[checked]="p.value"
(change)="toggle($event, $index)"
/>
如果我在将activeProblem分配给problem Group时使用@for渲染子组件,那么它就会失go 它的引用,从而实际上创建了对象的副本. 因此,我在子组件中所做的任何Mutations 都不会反映在原始对象中.
如果我使用 *ngFor指令渲染了子组件,那么它会按预期工作,我对problemGroup所做的任何更改都会有效地指向activeProblem.
我希望我能弄清楚为什么会发生这种情况?