ngFor

时间:2018-06-23 05:21:22

标签: angular ngfor angular6 form-control angular2-databinding

我正在从事一个项目,在这个项目中,我从后端收到多个选项的问题。现在,在问题类型之一-多选网格问题中,我们试图创建这样的视图

enter image description here

在html中,我已经编写了这段代码,

<!-- Multi choice grid questions -->
          <div *ngIf="(quiz['quizObj']['questionType'] === questionType.MULTI_CHOICE_GRID)">
            <div *ngFor="let ques of quiz['quizObj']['questionArray']; let i=index">
              <span>{{ques['questionRow']}}</span>
              <mat-radio-group [formControl]="selectedMultiChoiceGridOption"
                               (change)="onChangeOption(ques)">
                <mat-radio-button class="example-radio-button"
                                  *ngFor="let option of quiz['quizObj']['options']"
                                  [value]="option" [checked]="checkMultiChoiceGridSelectedOption(option, ques)">
                  {{option.option}}
                </mat-radio-button>
              </mat-radio-group>
            </div>
          </div>

在change事件中,我只是将特定问题和所选选项推入数组。

multiChoiceGridAnswers = [];
selectedMultiChoiceGridOption = new FormControl();
/* Multi choice grid question event - on change or on selecting any option */
  onChangeOption(quesRow: any) {
    const params = {
      questionRow: quesRow,
      selection: this.selectedMultiChoiceGridOption.value
    };
    const index = this.multiChoiceGridAnswers.findIndex((question) => {
      return (quesRow['questionRowId'] === question['questionRow']['questionRowId']);
    });
    if (index === -1) {
      this.multiChoiceGridAnswers.push(params);
    } else {
      this.multiChoiceGridAnswers[index] = params;
    }
  }

到现在为止一切正常,但是当我转到另一个问题并再次回来时,我面临一个问题。再次回到这个问题时,我又一次通过先前选择的选项创建一个数组,并从该数组中检查用户是否先前已检查过特定选项。

/* In the Multi choice grid question type, getting status if particular option is previously selected */
  checkMultiChoiceGridSelectedOption(option: any, ques: any) {
    let isSelected = false;
    if (this.multiChoiceGridAnswers.length > 0) {
      this.multiChoiceGridAnswers.filter((answerData) => {
        if ((answerData['questionRow']['questionRowId'] === ques['questionRowId'])) {
          if (answerData['selection'] && (answerData['selection']['optionId'] === option['optionId'])) {
            isSelected = true;
          }
        }
      });
    }
    return isSelected;
  }

但是我的观点是这种回应-

enter image description here

我相信这是因为表单控件不是唯一的,因为对于第二个问题,即使checkMultiChoiceGridSelectedOption函数也返回false “问题第2行”-“ true”选项,但仍认为是true。还有其他方法可以在ngFor内绑定数据吗? (ngModel也不起作用。)

谢谢。

0 个答案:

没有答案