Как связать три различных ввода, используя ngModel в angular? - PullRequest
0 голосов
/ 29 января 2020

У меня есть 3 разных ngModel, которые последовательно отображаются в модальном окне, поэтому CURRENT_TEXT и ALLERGY_DETAILS всегда получают одно и то же значение при изменении i fini sh, есть ли лучший способ выполнить эту задачу, используя ngModel или i я что-то упустил?

app.component. html

<div class="form-group" *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" class="form-control"  name="allerdydetail" placeholder="answerText" [(ngModel)]="ALLERGY_DETAILS.answerText">
    </div>
    </div>
</div>
<div class="form-group" *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" class="form-control"  name="currentText" placeholder="Text" [(ngModel)]="CURRENT_TEXT.answerText">
        </div>
    </div>
</div>
<div class="form-group" *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; trackBy:trackByIndex;">
            <label for="subQuestionsInput">{{ques.questionText}}</label>
            <!-- <input class="form-control" [(ngModel)]="ques.question[i]" [ngModelOptions]="{standalone: true}"> -->
            <input type="subQuestionsInput" class="form-control" *ngIf= "ques.answerType === 'TEXT_NUMBER'" name="TEXT_NUMBER" placeholder="Enter Dose amount Left"  [(ngModel)]="TEXT_NUMBER.answerText">
            <input type="subQuestionsInput" class="form-control" *ngIf= "ques.answerType === 'TEXT_DATE'" name="TEXT_DATE" placeholder="Enter Next Dose Date" [(ngModel)]="TEXT_DATE.answerText"> 
        </div>
    </div>
    </div>
</div>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @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 = [];
  TEXT_DATE: any;
  TEXT_NUMBER: any;
  CURRENT_TEXT: any;
  ALLERGY_DETAILS: any;
  showSubQuestionsCommon: boolean = false;

  constructor(private dataService:ApiService, private eventService:EventService) {
    this.questions = this.dataService.getData();
      this.TEXT_DATE = {
        "answerOptionId": 0,
        "answerText": "",
        "answerOptionId2": 0
    };
      this.TEXT_NUMBER = {
        "answerOptionId": 0,
        "answerText": "",
        "answerOptionId2": 0
    };
      this.CURRENT_TEXT =  {
        "answerOptionId": 0,
        "answerText": "",
        "answerOptionId2": 0
    };
      this.ALLERGY_DETAILS = {
        "answerOptionId": 0,
        "answerText": "",
        "answerOptionId2": 0
    };
  }
}

1 Ответ

0 голосов
/ 30 января 2020

Просто используйте реактивные формы, как предложено в комментарии выше, в компоненте ur создайте новый ALLERGY_DETAILS formControl:

component.ts

ALLERGY_DETAILS: FormControl = new FormControl('',Validators.required)
// remove the second parameter in case the value is not required
// to get the input value use 
this.ALLERGY_DETAILS.value;

затем в HTML шаблоне свяжите элемент ввода с контроллером:

компонент. html

<input type="subQuestionsInput" class="form-control"
  name="allerdydetail" placeholder="answerText" 
  [formControl]="ALLERGY_DETAILS">

наконец импортируйте ReactiveFormsModule в вашем приложении .module.ts

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...