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

Я получаю массив вопросов, которые я последовательно заполняю в модальном окне, поэтому входные данные, которые у меня есть в formGroup, основаны на вопросах, поэтому я пытаюсь назначить значения, как вы можете видеть, метод formatSubQuestions, когда каждый раз ответ на один вопрос представлен с использованием getNextQuestion. Проблема в том, что CURRENT_TEXT всегда содержит пустую строку, а TEXT_NUMBER и TEXT_DATE всегда имеют одинаковые значения. Только ALLERGY_DETAILS всегда получают правильные значения. Все эти входные данные не могут быть частью одного и того же вопроса. Что такое правильный подход? Я чешу голову, так как вчера любая помощь будет принята.

app.component. html

<form [formGroup]="questionForm" (ngSubmit)="onSubmit()">
                                  <div class="form-group">
                                      <label for="firstName">{{singleQuestion.questionText}}</label> 
                                  </div>
                                  <div class="form-group">
                                      <label for="nonClinicalInd">nonClinicalIndicator</label>
                                      <h5>{{singleQuestion.nonClinicalIndicator}}</h5>
                                      <!-- <input type="text" class="form-control" name="firstName" [(ngModel)]="question.questionText"/> -->
                                  </div>
                                  <div class="form-group">
                                    <label>answerOption</label>
                                      <div class="form-group" *ngFor="let option of singleQuestion.answerOption">
                                          <label>
                                            <input type="radio" name="answer-question-radio-btn"
                                            [value]="option.answerOptionId" (change) ="handleChange(option)">
                                            {{option.answerText}}
                                          </label>
                                        </div>
                                  </div>
                                  <div formGroupName="alrgyDetls" *ngIf="showSubQuestions">
                                      <div  *ngFor="let option of singleQuestion.answerOption">
                                        <div *ngFor="let sub of option.subQuestion">
                                          <label for="subQuestionsInput">{{sub.questionText}}</label>
                                          <input type="subQuestionsInput" name="allerdydetail" placeholder="answerText" formControlName="ALLERGY_DETAILS">
                                        </div>
                                      </div>
                                    </div>
                                    <div formGroupName="curntText" *ngIf="showSubQuestionsCommon">
                                        <div  *ngFor="let option of singleQuestion.answerOption">
                                          <div *ngFor="let sub of option.subQuestion">
                                            <label for="subQuestionsCommon">{{sub.questionText}}</label>
                                            <input type="subQuestionsCommon"   name="currentText" placeholder="Text" formControlName="CURRENT_TEXT">
                                          </div>
                                        </div>
                                  </div>
                                  <div formGroupName="DosesForm" *ngIf="showSubQuestionsQues"> 
                                    <div  *ngFor="let option of singleQuestion.answerOption">
                                      <div *ngFor="let sub of option.subQuestion">
                                          <div *ngFor="let ques of sub.question">
                                              <label for="subQuestionsInput">{{ques.questionText}}</label>
                                              <!-- <input class="form-control" [(ngModel)]="ques.question[i]" [ngModelOptions]="{standalone: true}"> -->
                                              <input type="subQuestionsInput"  *ngIf= "ques.answerType === 'TEXT_NUMBER'" name="TEXT_NUMBER" placeholder="Enter Dose amount Left"  formControlName="TEXT_NUMBER">
                                              <input type="subQuestionsInput"  *ngIf= "ques.answerType === 'TEXT_DATE'" name="TEXT_DATE" placeholder="Enter Next Dose Date" formControlName="TEXT_DATE"> 
                                          </div>
                                      </div>
                                      </div>
                                  </div>
                                  <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button type="button" *ngIf="showNextButton" [disabled]="!questionsOptionSelected" (change) ="handleChange(singleQuestion)" class="btn btn-primary" (click)="getNextQuestion(singleQuestion)">Next Question</button>
                                    <button type="button" *ngIf="showSaveButton" class="btn btn-primary" data-dismiss="modal" #closeBtn [disabled]="!questionsOptionSelected"  (change) ="handleChange(singleQuestion)" (click)="saveChanges(singleQuestion)">Save changes</button>
                                  </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[] = [];
  showSaveButton: boolean = false;
  showNextButton: boolean = true;
  showSubQuestions: boolean = false;
  currentSelectedItem: any;
  questionsOptionSelected: boolean = false;
  showSubQuestionsQues: boolean = false;
  questionsArray: any =[];
  subQuestionsAnswertext: any = [];
  showSubQuestionsCommon: boolean = false;
  FormValues: any;

  constructor(private dataService:ApiService, private eventService:EventService, private formBuilder: FormBuilder) {
    this.questionForm = this.formBuilder.group({
      alrgyDetls: formBuilder.group({
        ALLERGY_DETAILS: ['']
      }),
      curntText :this.formBuilder.group({
        CURRENT_TEXT: ['']
      }),
      DosesForm :this.formBuilder.group({
        TEXT_NUMBER: [''],
        TEXT_DATE: ['']
      }),
    });
  }
// nextQuestion button logic for single question event
 getNextQuestion(e: any){
  let formattedQuestion = {};
  this.questions.shift();
  formattedQuestion = this.formatSubQuestions(e.answerOption.subQuestion);
  if(formattedQuestion){
    this.questionsArray.push(formattedQuestion);
    this.questionsOptionSelected = false;
  }
   if(this.questions.length > 0){
      this.singleQuestion = this.questions[0];
      if(this.questions.length === 1) {
        this.showNextButton = false;
        this.showSaveButton = true;
    }
  }    
 }
 onSubmit(){
    this.FormValues = this.questionForm.value;
    console.log("Form", this.FormValues.value);
 }

 // if question has subQuestions this logic will apply 
 formatSubQuestions(subQuestion: any) {
   const answerOption = {
      "answerOptionId": "0",
      "answerText": "",
      "answerOptionId2": "0"

   }
   const _formattedSubQuestions = [];
  for (let sub of subQuestion){
    if (sub.responseFieldIdentifier === "ALLERGY DETAILS"){
        sub.answerOption = answerOption;
        sub.answerOption.answerText = this.FormValues.get('alrgyDetls.ALLERGY_DETAILS').value;
        console.log('sub', sub);
        _formattedSubQuestions.push(sub);
    }    
    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.FormValues.get('DosesForm.TEXT_NUMBER').value;
          _formattedSubQuestions.push(ques);
        } else if (ques.responseFieldIdentifier ===  "NEXT DOSE") {
          ques.answerOption = answerOption;
          ques.answerOption.answerText = this.FormValues.get('DosesForm.TEXT_DATE').value;
          _formattedSubQuestions.push(ques);
        }

      }
    }
    if(sub.nonClinicalIndicator === "N") {
      sub.answerOption = answerOption;
      sub.answerOption.answerText = this.FormValues.get('curntText.CURRENT_TEXT').value;
      console.log('sub', sub);
        _formattedSubQuestions.push(sub);
      }
    }
    this.showSubQuestions = false;
    this.showSubQuestionsQues = false;
    this.showSubQuestionsCommon = false;
    return _formattedSubQuestions;
  }

  // save changes and emit data to format component
 saveChanges(e:any){
  this.getNextQuestion(e);
  this.eventService.setData(this.questionsArray);
  this.questions = [];
  this.singleQuestion = [];
  this.questionsArray = [];
  this.closeBtn.nativeElement.click();
 }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...