Angular 重新渲染仅使用 ngrx 更改表中的行

标签 angular html-table ngrx

我正在使用 NGRX 将数据从远程 api 加载到数组中,然后在经典 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,这会更改数组的一行,所有表格都会再次呈现(导致一些闪烁)。

有没有办法告诉 Angular 仅渲染数组中已更改的行?

解决方案(感谢@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。这是告诉 Angular 仅渲染数组中已更改的行的方法。

请在此处阅读更多相关信息 How to use trackBy with ngFor 或在这里查看示例 Explain ngFor trackBy in Angular

关于Angular 重新渲染仅使用 ngrx 更改表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74245858/

相关文章:

javascript - lodash 基于多种条件的 Groupby

javascript - Angular 旭日图

html - 表格单元格上的额外空白

html - 如何将我的悬停样式限制为仅按钮而不是整个表格行?

javascript - *ngIf 内的 viewChild 产生 undefined reference

RxJS 6/tap 运算符何时发出值

java - 从rest api下载文件而不需要window.open

angular - 从 this.router.events.subscribe() 中获取多个项目

html - 使用 HTML 和 CSS 布局一个小表格

Angular NgRx - 在效果中使用 store.dispatch 是不好的做法吗?