Как связать значения с помощью angular реактивных форм? - PullRequest
0 голосов
/ 31 января 2020

Я пытаюсь динамически связать входные значения, поэтому ниже вводятся значения, основанные на вопросах данных, поэтому есть два вопроса, которые мне нужны, чтобы получить значения и привязать к FormControl, но я вижу, что значения назначаются, однако, когда я получаю возвращаемый массив из formatSubQuestions оба входа возвращают одно и то же значение, введенное последним. Любая идея, где я делаю ошибку, чтобы сделать правильную привязку?

app.component. html

<form [formGroup]="questionForm">
 <div *ngIf="showSubQuestionsQues"> 
                                    <div  *ngFor="let option of singleQuestion.answerOption">
                                      <div *ngFor="let sub of option.subQuestion">
                                          <div *ngFor="let ques of sub.question; let i= index">
                                              <label for="subQuestionsInput">{{ques.questionText}}</label>
                                              <div formGroupName="textNum">
                                                <input type="subQuestionsInputNum" class="form-control" *ngIf= "ques.answerType === 'TEXT_NUMBER'" name="TEXT_NUMBER" placeholder="Enter Dose amount Left"  formControlName="TEXT_NUMBER">
                                              </div>
                                              <div formGroupName="textDate">
                                                <input type="subQuestionsInputText"  class="form-control" *ngIf= "ques.answerType === 'TEXT_DATE'" name="TEXT_DATE" placeholder="Enter Next Dose Date" formControlName="TEXT_DATE"> 
                                              </div>  
                                          </div>
                                      </div>
                                      </div>
                                  </div>
                              </form>

app.component.ts

import { Component, ViewChild, ElementRef} from '@angular/core';
import { ApiService } from './api.service';
import { EventService} from './format-questions/format-questions.service'
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  questionForm: FormGroup;
  @ViewChild('closeBtn', {static: false}) closeBtn: ElementRef;
  data: any;
  questions: any[] = [];
  singleQuestion: any[] = [];

  constructor(private dataService:ApiService, private eventService:EventService, private formBuilder: FormBuilder) {
    this.questionForm = this.formBuilder.group({
      textNum :this.formBuilder.group({
        TEXT_NUMBER: [''],
      }),
      textDate :this.formBuilder.group({
        TEXT_DATE: ['']
      }),
    });
  }
// nextQuestion button logic for single question event

formatSubQuestions(subQuestion: any) {
   const answerOption = {
      "answerOptionId": "0",
      "answerText": "",
      "answerOptionId2": "0"

   }
   const _formattedSubQuestions = [];
  for (let sub of subQuestion){   
    if(Array.isArray(sub.question) && sub.question.length) {     
      for( let ques of sub.question) {
        if(ques.responseFieldIdentifier === "DOSE LEFT") {
          ques.answerOption = answerOption;
          ques.answerOption.answerText = this.questionForm.get('textNum.TEXT_NUMBER').value;
          _formattedSubQuestions.push(ques);
        } else if (ques.responseFieldIdentifier ===  "NEXT DOSE") {
          ques.answerOption = answerOption;
          ques.answerOption.answerText = this.questionForm.get('textDate.TEXT_DATE').value;
          _formattedSubQuestions.push(ques);
        }

      }
    }
    return _formattedSubQuestions;
  }
  // save changes and emit data to format component
 saveChanges(e:any){
 const finalResponse=  this.formatSubQuestions(e);
  this.eventService.setData(finalResponse);
 }
}

data

{
    "nonClinicalIndicator": "Y",
    "questionId": 258,
    "questionId2": 1738,
    "questionText": "How much of your medication(s) do you have left? For insurance purposes you must provide exact number of pills, injections, doses etc",
    "answerId": 0,
    "answerType": "SINGLE_SELECT",
    "responseFieldIdentifier": "DOSE LEFT IND",
    "answerOption": [{
            "answerOptionId": 2559,
            "answerOptionId2": 1639,
            "answerText": "Yes",
            "subQuestion": [{
                "question": [{
                        "nonClinicalIndicator": "Y",
                        "questionId": 2560,
                        "questionId2": 18740,
                        "questionText": "Quantity remaining",
                        "answerId": 0,
                        "answerType": "TEXT_NUMBER",
                        "responseFieldIdentifier": "DOSE LEFT"
                    },
                    {
                        "nonClinicalIndicator": "Y",
                        "questionId": 2561,
                        "questionId2": 16141,
                        "questionText": "When will you take your next dose?",
                        "answerId": 0,
                        "answerType": "TEXT_DATE",
                        "responseFieldIdentifier": "NEXT DOSE"
                    }
                ]
            }],
            "isChecked": false
        },
        {
            "answerOptionId": 2562,
            "answerOptionId2": 142,
            "answerText": "No",
            "isChecked": false
        }
    ]
}
...