angular *ngFor 不使用输入重新渲染 html 表

Kis*_*Oza 3 javascript angular

我遇到了一个非常奇怪的角度问题。我在我的 ts 文件中创建了一个简单的数组,我通过迭代同一个数组来显示一个带有输入的表。现在,当我更改数组(反转它)时,它工作正常,但是如果我在更改之前在输入中输入了某些内容,则文本将保留在输入中。

这是代码

component.ts

    import { Component } from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'practice';
      myArray = [1,2,3,4,5,6,7];
      change() {
        // this.myArray = [];
        this.myArray.reverse();

      }
    }
Run Code Online (Sandbox Code Playgroud)

我的 HTML:

    import { Component } from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'practice';
      myArray = [1,2,3,4,5,6,7];
      change() {
        // this.myArray = [];
        this.myArray.reverse();

      }
    }
Run Code Online (Sandbox Code Playgroud)

问题说明示例视频:https : //www.loom.com/share/6f4887183bb94150ad7390f25e5b466a

如您所见,当我在输入中输入内容并更改数组时,该值仍保留在数组中。我已经检查过原始数组没有改变。

我的意思是它只是被逆转了,但没有别的。

问题是什么?

Fat*_*zli 6

您应该使用trackby

<table>
    <tr *ngFor="let item of myArray; let i = index ;trackBy: trackItem" >
      <td>
        <input type="text" [value]='item' >
      </td>
    </tr>
  </table>
  <button (click)="change()">Change</button>
Run Code Online (Sandbox Code Playgroud)

在 ts:

trackItem (index, item) {
    return this.myArray ? this.myArray : undefined;
  }
Run Code Online (Sandbox Code Playgroud)

如果你想保留那个值,你应该使用 ngModel 绑定它:

<table>
    <tr *ngFor="let item of myArray; let i = index ;trackBy: trackItem" >
      <td>
        <input type="text" [value]='item' [(ngModel)]="myArray[i]" >
      </td>
    </tr>
  </table>
  <button (click)="change()">Change</button>
Run Code Online (Sandbox Code Playgroud)

检查这个演示

为什么使用 trackby

默认情况下,当您使用不带 trackBy 的 *ngFor 时,*ngFor 会跟踪通过对象标识更改的对象数组。因此,如果对象数组的新引用传递给指令,即使数组具有相同的值,Angular 也无法检测到它们已经在当前 DOM 中绘制和呈现。相反,旧元素将被删除并重绘具有相同值的新集合。我们可以通过提供 trackBy 函数来帮助 Angular 跟踪添加或删除了哪些项目。trackBy 函数将索引和当前项作为参数,并需要返回该项的唯一标识符。现在,当您更改集合时,Angular 可以根据唯一标识符跟踪已添加或删除的项目,并仅创建或销毁更改的项目。

在以下情况下使用 trackBy:

1 - 迭代大型对象集合

2 - 您的业务逻辑可能需要通过重新排序、修改特定项目、删除项目或添加新项目来修改任何这些元素

  • 如果你想更好地理解它,这是一篇很好的[文章](https://blog.bitsrc.io/angular-optimization-use-trackby-option-for-ngfor-directive-72c9509b2be9)。 (2认同)