首页 > 解决方案 > 更改表行中的 [(ngModel)] 值将影响正文中存在的所有行。如何修复它?

问题描述

我有一个用 *ngFor 生成的表。现在在那个表里面我有 2 列和 5 行。第一列包含一个选择标签,第二列将显示选定的值。现在的问题是,当您在任何行的选择标记中选择任何值时,所选值会显示在所有行中。

为了更好地理解问题,请参阅https://stackblitz.com/edit/angular-43oxrc

app.component.ts

categoryCall(categoryName) {
    if (categoryName == 1) {
      this.categories = ["Value 1", "Value 2", "Value 3"];
    }
    else if (categoryName == 2) {
      this.categories = ["Value 4", "Value 6", "Value 5", "Value 7"];
    }
    else if (categoryName == 3) {
      this.categories = ["Value 7", "Value 8"];
    }
    return this.categories;
  }

app.component.html

<table>
          <tbody>
            <tr *ngFor="let item of [1,2,3,4,5]">
              <td>
                <select [(ngModel)]="selectedCategory">
                  <option *ngFor="let category of categoryCall(item)" [ngValue]="category">{{category}}</option>
                </select>
              </td>
              <td>
                Choosen Value: {{selectedCategory}}
              </td>
            </tr>
          </tbody>
        </table>

我需要喜欢;如果您在第一行选择任何值,那么它的值应该只显示在它自己的第一行。它不应反映在任何其他行中

标签: javascriptangular

解决方案


你不能那样做。 原因是 selectedCategory 绑定到所有五个位置,因为它是一个值。你可以这样做。

TS

export class AppComponent  {
  selectedCategory: string;
  categories: string[];
  items = [];

  constructor () {
    this.addItems();
  }

  addItems() {
    for (let i = 0; i < 5; i++) {
      this.items.push({selectedCategory: null, number: i + 1});
    }
  }
}

HTML

<table>
  <tbody>
    <tr *ngFor="let item of items">
      <td>
        <select [(ngModel)]="item.selectedCategory">
          <option *ngFor="let category of categoryCall(item.number)" [ngValue]="category">{{category}}</option>
        </select>
      </td>
      <td>
      Choosen Value: {{item.selectedCategory}}
      </td>
    </tr>
  </tbody>
</table>

StackBlitz 演示


推荐阅读