带有 cdkDropList 的 Angular Material 垂直步进器问题与表单输入名称

AngularMaterial vertical stepper with cdkDropList issue with form input names

我正在用 angular material 做一个 dropList,我遇到了以下问题:

最初:

我使用 ngForm 的索引作为表单属性名称的值,如果我更改末尾空元素的位置(用鼠标移动)然后删除它,我得到这个:

视觉上它工作正常,但是如果我们查看 ngForm 字段的值,我们会发现这些值不正确,因为在删除元素后名称尚未更新

解决这个问题的一种方法是在 name 属性中添加 Math.random,但这似乎不是很好的解决方案

有什么办法可以解决这个问题?

https://stackblitz.com/edit/angular-hipzr9

如果您在拖放方法中 console.log 您的 event.container.datathis.form.contactFormSections,您将在列表中拖放后看到它们都匹配。

drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);

    console.log(event.container.data);
    console.log(this.form.contactFormSections);
  }

您的逻辑得到 "decoupled" 的地方是因为您在 html #formBuild="ngForm" 中使用模板驱动的表单...这是一个孤立的表单 "decoupled"来自组件

您需要利用 reactive forms 来解决这个问题。根据您的部分构建 FormGroup 并操作表单组,这将使您的基础数组 "coupled" 与视图保持同步并使所有内容保持同步。

https://angular.io/guide/reactive-forms

详细说明如何使用动态响应式表单并从中提交值。