You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular ngx-datatable打开模态框触发NG0100错误

问题代码与报错

HTML代码

<ngx-datatable-column *ngIf="search_type ==='booking'" [width]="50" [sortable]="false"
                  [canAutoResize]="false" [draggable]="false" [resizeable]="false">

                  <ng-template ngx-datatable-cell-template let-row="row" let-value="value">
                    <span class="fa fa-user-plus font-medium-3 text-primary cursor-pointer pl-1"
                      (click)="onUpdateBookingLinguist(row)"></span>
                  </ng-template>
                </ngx-datatable-column>

TypeScript代码

onUpdateBookingLinguist(linguist: Linguist) {

    const modalRef = this.modalService.open(ScheduledBookingModalComponent, { size: 'lg' });
    modalRef.componentInstance.linguist_other_bookings = linguist['scheduled_booking'];

    modalRef.result.then((result) => {

      if (!result) {
        return;
      }

      this.cdr.detectChanges();
    }).catch((e) => { });

    this.cdr.detectChanges();

  }

报错信息

ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'datatable-body-cell sort-active active'. Current value: 'datatable-body-cell sort-active'.

解决方案

这个错误源于打开模态框的操作在Angular当前变更检测周期内,触发了ngx-datatable单元格类名的二次变更,导致检测不通过。可以通过以下方式修复:

  • 将模态框打开逻辑放入setTimeout中,让操作脱离当前变更检测周期:
onUpdateBookingLinguist(linguist: Linguist) {
  setTimeout(() => {
    const modalRef = this.modalService.open(ScheduledBookingModalComponent, { size: 'lg' });
    modalRef.componentInstance.linguist_other_bookings = linguist['scheduled_booking'];

    modalRef.result.then((result) => {
      if (result) {
        this.cdr.markForCheck();
      }
    }).catch(() => {});
  });
}
  • 移除多余的detectChanges()调用,改用markForCheck():detectChanges()会强制同步触发检测,容易引发周期冲突;markForCheck()仅标记视图需要更新,由Angular在下一个周期自动处理,更安全。

内容的提问来源于stack exchange,提问作者Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:44:51