Angular 14 -如何打破formgroup在formmarray中的双向绑定?



我的问题在下面详细说明。我有一个垫子对话框,用于编辑以前的数据条目。每个条目都有一个可交付形式的FormGroup。一个FormControl名称,一个formmarray步骤。然后formmarray Steps有一个FormGroup和两个formcontrol。像这样:

// TOTALLY PSEUDO
Deliverable = FormGroup({
name: FormControl,
steps: FormArray[FormGroup({
step_num: FormControl,
step_name: FormControl
}), FormGroup({
step_num: FormControl,
step_name: FormControl
})]
})

编辑功能:


export interface Deliverable {
name: string,
steps: any[]
}
edit(deliverable: Deliverable) {
const tempSteps = Object.assign([], deliverable.steps)
const dialogRef = this.dialog.open(DeliverableDialogComponent, {
data: { name: deliverable.name, steps: tempSteps }
})
dialogRef.afterClosed().subscribe(result => {
console.log(result)
})
}

关于DeliverableDialogComponent.html:

<mat-dialog-content>
<mat-form-field class="form-field" appearance="outline">
<mat-label>Deliverable Name</mat-label>
<input matInput type="text" autocomplete="off" [(ngModel)]="data.name" />
</mat-form-field>
<div *ngFor="let step of data.steps; let stepIndex=index">
<mat-form-field class="form-field" appearance="outline">
<mat-label>Step Number</mat-label>
<input matInput type="text" autocomplete="off" [(ngModel)]="step.step_num">
</mat-form-field>
<mat-form-field class="form-field" appearance="outline">
<mat-label>Step Name</mat-label>
<input matInput type="text" autocomplete="off" [(ngModel)]="step.step_name">
</mat-form-field>
</div>
</mat-dialog-content>

关于DeliverableDialogComponent.ts:

import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
export interface Deliverable {
name: string;
steps: any[];
}
@Component({
selector: 'app-deliverable-dialog',
templateUrl: './deliverable-dialog.component.html',
styleUrls: ['./deliverable-dialog.component.scss']
})
export class DeliverableDialogComponent implements OnInit {
constructor(public dialogRef: MatDialogRef<DeliverableDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: Deliverable) { }
onNoClick(): void {
this.dialogRef.close()
}
ngOnInit(): void {
}
}

我的问题是step_num和step_name两个步骤都有双向连接。因此,当我在对话框中进行更改时,它正在更新原始组件上的step_num和step_name。我不想要这个功能,因为我只希望它更新,当我点击保存,而不是更新,当我点击取消或只是点击退出对话框。Deliverable.name工作得很好,但是步骤是双向绑定的。

我通过深度复制可交付内容来解决这个问题。步骤如下:

const tempSteps = JSON.stringify(JSON.parse(deliverable.steps))
//INSTEAD OF
const tempSteps = Object.assign([], deliverable.steps)

相关内容

  • 没有找到相关文章

最新更新