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
相关产品推荐
相关产品推荐

