拖放角度顺序不变

时间:2020-04-13 05:21:57

标签: angular angular-material angular-cdk angular-cdk-drag-drop

我基于此https://stackblitz.com/edit/angular-dynamic-survey-creation-golkhg创建表单构建器,并使用此功能进行投递

onDrop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.surveyForm.get('surveyQuestions')['controls'], event.previousIndex, event.currentIndex);
}

questionTitle必须更改,但没有更改

enter image description here

但是在html中它正在改变

enter image description here

数组的顺序在html中正在更改,但是在我的json中没有更改,有人可以帮助我吗?

编辑

过一会儿,我不再触摸此代码,我发现了一些错误,请在图像前后查看,这里是

Before

"quizQuestions": [
    {
      "questionType": "File Upload",
      "display_order": 1,
      "questionGroup": {
        "questionTitle": "",
        "quizAnswer": ""
      }
    },
    {
      "questionType": "Tanggal",
      "display_order": 2,
      "questionGroup": {
        "questionTitle": "",
        "quizAnswer": ""
      }
    }
  ],

我拖动第一个表格后,看起来像这样

After

"quizQuestions": [
    {
      "questionType": "Tanggal",
      "display_order": 2,
      "questionGroup": {
        "questionTitle": "",
        "quizAnswer": ""
      }
    },
    {
      "questionType": "File Upload",
      "display_order": 1,
      "questionGroup": {
        "questionTitle": "",
        "quizAnswer": ""
      }
    }
  ],

实际上出了什么问题?我已经尝试了你们提供的两个最佳解决方案,但仍然是这样,请帮帮我。注意:我将surverysQuestions更改为quizQuestions

3 个答案:

答案 0 :(得分:2)

您需要在formGroup中添加display_order属性,您可以在该属性中看到订单更改。

然后在onDrop方法中更改其他问题的显示顺序。像这样的东西:

onDrop(event: CdkDragDrop<string[]>) {
   moveItemInArray(this.surveyForm.get('surveyQuestions')['controls'], event.previousIndex, event.currentIndex);
   this.questionFormArray.controls[event.currentIndex]['controls']['display_priority']
            .setValue(event.currentIndex + 1);
   this.questionFormArray.controls.forEach((category, index) => {
            (category as FormGroup).controls['display_priority'].setValue(index + 1);
   });
}

答案 1 :(得分:0)

尝试向您的组件添加changeDetectionStrategy

https://angular.io/api/core/ChangeDetectionStrategy

答案 2 :(得分:0)

方法示例:

onDrop(event: CdkDragDrop<string[]>) {
   moveItemInArray(this.surveyForm.get('surveyQuestions')['controls'], event.previousIndex, event.currentIndex);
  this.surveyForm.get('surveyQuestions').updateValueAndValidity({ onlySelf: false });
}