首页 > 解决方案 > 嵌套 *ngFor 中的 Angular 4 ngModel 绑定

问题描述

您好,我遇到了一个问题,我无法将数据绑定到您将在此嵌套 *ngFor 中看到的“已选择”值。这里发生的事情是我有一个可能的害虫(虫子等)的列表,对于每个害虫我都有一个我必须问这个人的问题列表。因此,当我遍历每个选定的害虫,然后进入每个问题(某些害虫有相同的问题)时,它会将一种害虫的答案与具有相同问题的所有其他害虫联系起来。无论我尝试什么,都不允许我将选定的答案绑定到特定的害虫而不是剩余的害虫。这是我的 HTML:

这是我要开始工作的工作的 Stackblitz。就像在 stackblitz 中一样,我有一系列问题要推到害虫的数组中。

STACKBLITZ Angular 应用程序

  <div *ngFor="let each of selectedPestProblems; let x = index;">
    <div *ngIf="selectedPest === x" class="pestQuestions">
      <div *ngFor="let questions of each.question; let i = index; trackBy:trackByIndex">
        <h4 *ngIf="i == 0" style="padding-left: 15px;"><br>{{each.pest}}</h4>
        <label>{{questions.question}}</label>
        {{x + " " + i}}
        <div *ngIf="questions.type == 'checkbox'" (click)="changeCheckBox2(x, i)">
          <input type="checkbox" class="css-checkbox" [(ngModel)]="selectedPestProblems[x].question[i].selected" name="checkbox{{i + '' + x}}">
          <label class="css-label"> - {{questions.title}}</label>
        </div>
        <div *ngIf="questions.type == 'select'">
          <select class="otherSelects" [(ngModel)]="selectedPestProblems[x].question[i].selected" name="select{{i + '' + x}}">
            <option *ngFor="let answers of questions.answer" [value]="answers.id">
              {{answers.name}}
            </option>
          </select>
        </div>
        <div *ngIf="questions.type == 'selectOther'">
          <select class="otherSelects" [(ngModel)]="selectedPestProblems[x].question[i].selected" name="selectOther{{i + '' + x}}">
            <option *ngFor="let answers of questions.answer" [value]="answers.id">
              {{answers.name}}
            </option>
          </select>
          <div *ngIf="questions.selected == 5">
            <br>
            <textarea [(ngModel)]="selectedPestProblems[x].question[i].description" placeholder="Tell Us Where It Is Located." name="description{{i + '' + x}}"></textarea>
          </div>
        </div>
        <br>
        <div *ngIf="i == selectedPestProblems[x].question.length - 1">
          <button (click)="removePestProblem(x)" style="margin-left: 15px;">Remove Pest Problem</button>
          <br>
        </div>
      </div>
    </div>
  </div>

那么这里是我循环遍历的数组的一个示例。

我的数组是什么样子的。

所以,这个数组只显示了我正在循环的一种害虫,我在底部有另一个害虫“蜜蜂”,发生的是我的复选框和选择框,我认为它应该被建模为每个害虫的​​每个问题的“选定”值,但是当我为其中一个选择答案时,它表明没有为具有相同问题的所有其他害虫选择该答案。

标签: angulartypescriptangular-ngmodel

解决方案


不要忘记,JavaScript/TypeScript 对象是引用类型。您将相同的问题对象推入两个不同的数组中,这并不意味着两者不同——两个对象都相同——就内存位置而言,它们的位置是相同的。

您可以使用 TypeScript 的 Object Spread 运算符使对象彼此不同 - 它们是不同的(不同的内存位置)。

ngOnInit(){
    for(var i = 0; i < this.selectedPestProblems.length; i++){
      this.selectedPestProblems[i].question.push({...this.question1});
      this.selectedPestProblems[i].question.push({...this.question2});
    }
  }

[只是一个旁注,它是一个不同的级别]

我已经用解决方案分叉了你的 stackblitz 代码。 https://stackblitz.com/edit/angular-rphm3z?file=src/app/app.component.ts


推荐阅读