嵌套* ngFor中的Angular 4 ngModel绑定

时间:2018-06-01 16:29:44

标签: angular typescript angular-ngmodel

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

这是我正在尝试开展工作的Stackblitz。就像在stackblitz中一样,我有一系列问题,我将其推入害虫阵列。

STACKBLITZ ANGULAR APP

  <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>

然后这是我循环播放的数组的示例。

What my array looks like.

所以,这个数组只是显示了我正在经历的一种害虫,我有另一种害虫&#34;蜜蜂&#34;在底部,那里发生的是我的复选框和选择框,我认为它应该被建模到&#34;选择&#34;每种有害生物的每个问题的价值,但是当我选择其中一种有害生物的答案时,它表明没有为具有同一问题的其他每种有害生物选择该答案。

1 个答案:

答案 0 :(得分:1)

不要忘记,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