我正在使用NGRX将数据从远程API加载到一个数组中,然后将该数组呈现在一个classic 的HTML表中.部分代码如下所示:

  ngOnInit() {
    this.store
      .select(
        createSelector(
          (state: AppState) => state.userProperties,
          (propObject: UserProperties) => propObject
        )
      )
      .pipe(takeUntil(this.destroyed$))
      .subscribe(({properties, total }) => {
        this.propertyList = properties;
        this.totalFound = total;
      })

和呈现代码:

      <tbody>
        <ng-container *ngFor="let row of propertyList">
          <tr>
            <td>
            </td>
            <td class="limited">{{ row.id }}</td>
            <td class="limited">{{ categoryLabels[row.category] | _: trans.lang }}</td>
            <td class="limited">{{ contractLabels[row.contract_type] | _: trans.lang }}</td>
            <td class="limited">{{ row.price }}</td>
            <td class="limited">{{ row.city }}</td>
            <td class="limited">
            </td>
            <td>
              <div class="table-actions">
                <button (click)="editProperty(row.id)" class="button button-icon">
                  <edit-icon></edit-icon>
                </button>
                <button *ngIf="row.deleted === 0" (click)="archiveProperty(row.id)" title="Delete this property"
                  class="button button-icon">
                  <img src="/assets/images/icons/delete-red.svg" />
                </button>
                <button (click)="toggleExpand(row.id)" class="button button-icon btn-expand">
                  <expand-icon [expanded]="expandedElements[row.id]"></expand-icon>
                </button>
              </div>
            </td>
          </tr>
        </ng-container>

我注意到的问题是,如果我更改一行,例如我单击setStatus,这会更改数组的一行,所有表都会再次呈现(导致一些闪烁).

有没有一种方法可以告诉ANGLE只渲染数组中已更改的行?

解决方案(感谢@Dmytro Demyanenko): 将trackby添加到ngFor:

<ng-container *ngFor="let row of propertyList; trackBy: trackByFn">

并定义trackby函数:

  trackByFn(index, row) {
    return JSON.stringify(row);
  }

只有当trackBy函数返回与上次返回的值不同的值时,Angular 才会重新呈现ngFor循环元素.在我的例子中,行中的某些数据可能会更改,然后需要重新呈现.

推荐答案

是的,你能做到的.你可以用trackBy来代替ngFor.这是告诉ANGLE只渲染数组中已更改的行的方法.

请在这里阅读更多关于这方面的信息How to use trackBy with ngFor 或点击此处查看示例Explain ngFor trackBy in Angular

Angular相关问答推荐

在forkjoin中使用NGXS状态数据

在不使用散列(#)路由的情况下刷新Angular 8的SPA时,删除404错误

使用Angular 13的NgxPrinterService打印时,第二页上的空白区域

选中/取消选中-复选框未正确返回TRUE或FALSE

ANGLE DI useFactory将参数传递给工厂函数

倒计时计时器,每10秒重新启动一次,共4次

天使17中的倒计时器

如何将角17中的嵌套组件与独立组件一起使用?

列表和映射的SCSS语法

IonicStorageModule似乎不是 NgModule 类

Angular 按钮指令错误地附加子元素

Angular UNIVERSAL prerender 错误方法 Promise.prototype.then 调用不兼容的接收器 [object Object]

可观察的等待直到另一个可观察的值

ng14中具有强类型表单的FormBuilder

Angular模板错误:Property does not exist on type component

如何 use/import http模块?

如何在 Angular 5 HttpInterceptor 中添加多个标头

如何从 EventEmitter 函数返回值?

缺少带有Angular的语言环境XXX的语言环境数据

如何在 Angular 中使用带有 SASS 的 Bootstrap 4