How to dynamically add inputs value to angular component?

三世轮回 提交于 2020-02-06 08:02:06

问题


I am getting array of questions that i am populating sequentially in modal window so inputs i have in formGroup are based on questions , SO i am trying to assign values as you can see formatSubQuestions method when everytime sinle question answer submitted using getNextQuestion. The problem is CURRENT_TEXT always come empty string and TEXT_NUMBER and TEXT_DATE always have same values. Only ALLERGY_DETAILS always get correct values. All these inputs may not be part of same question. What is correct approach i am scratching my head since yesterday any any help would be appreciated.

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();
 }
}

来源:https://stackoverflow.com/questions/59990604/how-to-dynamically-add-inputs-value-to-angular-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!