首页 文章

嵌套* ngFor中的Angular 4 ngModel绑定

提问于
浏览
0

您好我有一个问题,我无法将数据绑定到您将在此嵌套* ngFor中看作我的“Selected”值 . 这里发生的事情是我列出了可能的害虫(虫子等),对于每种害虫我都有一个问题列表,我必须要问这个人 . 因此,当我遍历每个选定的害虫,然后进入每个问题(其中一些害虫具有相同的问题)时,它将一种害虫的答案与所有其他害虫的答案绑定在一起 . 无论我尝试什么,它都不允许我将选定的答案绑定到特定的害虫而不是剩余的害虫 . 这是我的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.

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

1 回答

  • 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

相关问题