表单控件将值作为对象数组获取

form control getting value as an array of objects

基本上我有一个带有问题的表单和一个答案输入字段,如下面的屏幕截图所示。

如何使用 formcontrol 将问题 ID 和答案作为对象数组获取,在下面的预期输出中具有相同的结构。

对象的答案是每个文本区域字段的答案,qid 是问题的 qid。任何想法将不胜感激。谢谢。

#html代码

     <form *ngIf="modelForm" [formGroup]="modelForm">
        <div *ngFor="let q of questions;let i = index;" >
            <div class="confirm-detail-two">
                <div class="p-label">{{q.question}}</div>
            </div>
            <mat-form-field appearance="fill" class="details-field-container" style="padding-bottom:10px;">
                <mat-label>Details</mat-label>
                <textarea class="details-textarea" formControlName="questionAnswer" matInput matInput></textarea>
            </mat-form-field>
          </div>
      </form>

#我正在循环的问题列表

  const questions = [
    {
        "qid": 1,
        "question": "What is my name ?"
    },
    {
        "qid": 10,
        "question": "Where do I live?"
    }
]

#tscode

 ngOnInit(): void {       
    this.modelForm = this._createModelForm();
  }

  private _createModelForm(): FormGroup {
    return this.formBuilder.group({
      accountId:this.model.accountId,
      questions:[this.model.questions || []],
      questionAnswer:[this.model.questionAnswer || []],
    });
  }

#expected output - this.modelform.value ,这应该是用户向每个对象添加答案后的数据结构 field.The 来自对象的答案是来自每个文本区域字段的答案,qid 是来自问题的 qid。

{
     "questionAnswer": [{
        "qid" :1,
        "answer" :"Josh"
        },
        {
        "qid" :10,
        "anwer" :"New York"
        }],
}

#expected output - the this.modelform.value , this should be the data structure after the user add answer to each field.The answer from the object is the answer from each text area fields and the qid is the qid from the questions.

我认为在不涉及对象转换的情况下使用 FormBuilder 构建这样的答案模型是不可能的。

对于你的情况,我会做什么:

  1. questions转换为FormBuilder对象
  2. 将表单值转换为 questionAnswer
questions = [
    {
      qid: 1,
      question: 'What is my name?',
    },
    {
      qid: 10,
      question: 'Where do I live?',
    },
  ];

/**
 * Created mapping qid to answer
 */
private _createModelForm(): FormGroup {
    const idToAnswerMap = this.questions.reduce((acc, question) => {
      return {
        ...acc,
        [question.qid]: '', // default answer is blank
      };
    }, {});

    return this.formBuilder.group(idToAnswerMap);
  }

填写表格后,如果我执行this.modelForm.value,我会得到以下

{1: "answer 1", 10: "answer 2"}

// 1 is qid for question 1, 10 is qid for question 2, etc

据此,构造 questionAnswer

的对象
const formValues = this.modelForm.value;

const finalAnswer = {
  questionAnswer: Object.keys(formValues).map((qid) => ({
    qid: Number(qid),
    answer: formValues[qid],
  })),
};

console.log(finalAnswer)

我会得到你想要的相同结果

{
  "questionAnswer": [
    { "qid": 1, "answer": "answer 1" },
    { "qid": 10, "answer": "answer 2" }
  ]
}

在这里查看我的 Stackblitz