Angular 将元素的宽度传递给我自己的指令时,ExpressionChangedTerithasBeenCheckedError。

Angular 将元素的宽度传递给我自己的指令时,ExpressionChangedTerithasBeenCheckedError。,angular,angular-directive,angular2-hostbinding,Angular,Angular Directive,Angular2 Hostbinding,我为表头创建了自己的指令(thead标记)。这使得表格的标题是“粘滞的”(有固定的位置,在滚动表格时可见)。看起来是这样的: sticky.directive.ts const NAVBAR_HEIGHT = 55; @Directive({ selector: '[sticky]', }) export class StickyDirective implements AfterViewInit { @Input() @HostBinding('style.widt

我为表头创建了自己的指令(thead标记)。这使得表格的标题是“粘滞的”(有固定的位置,在滚动表格时可见)。看起来是这样的:

sticky.directive.ts

const NAVBAR_HEIGHT = 55;

@Directive({
    selector: '[sticky]',
})
export class StickyDirective implements AfterViewInit {

    @Input()
    @HostBinding('style.width.px')
    stickyWidth: string;

    topPosition: number;

    constructor(private _element: ElementRef, private _window: WindowRef) { }

    ngAfterViewInit() {
        let boundingClientRect = this._element.nativeElement.getBoundingClientRect();
        this.topPosition = boundingClientRect.top - NAVBAR_HEIGHT;
    }

    @HostListener('window:scroll', ['$event'])
    handleScrollEvent(e) {
        if (this._window.nativeWindow.pageYOffset > (this.topPosition) ) {
            this._element.nativeElement.classList.add('stick');
        } else {
            this._element.nativeElement.classList.remove('stick');
        }
    }
} 
并以这种方式被称为

<div class="card-block" >
   <table #table class="table table-bordered">
      <thead sticky [stickyWidth]="table.offsetWidth">


谁能解释我做错了什么?如何保护我的应用程序不受此异常的影响,或者创建类似指令的正确方法是什么?提前感谢您更新
表格的那一刻。offsetWidth
将在Angular完成其
更改检测
周期后发生

共享代码会更好,但在看不到代码的情况下,您可能需要执行以下操作:

  • 以更好和适当的时间移动更新,并确保更改过程是单向的

  • 更新后使用
    detectorRef.detectChanges()

  • 将更新放在setTimeout内


其中任何一个都可以,但最好的是第一个,其他的是您在更新
表时的最后手段。offsetWidth
在Angular完成其
变更检测
周期后发生

共享代码会更好,但在看不到代码的情况下,您可能需要执行以下操作:

  • 以更好和适当的时间移动更新,并确保更改过程是单向的

  • 更新后使用
    detectorRef.detectChanges()

  • 将更新放在setTimeout内

其中任何一个都可以,但最好的是第一个,其他的是你最后的选择

这篇文章非常详细地解释了这种行为这篇文章非常详细地解释了这种行为
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '1632'. Current value: '1615'.
    at viewDebugError (core.es5.js:8633)
    at expressionChangedAfterItHasBeenCheckedError (core.es5.js:8611)
    at checkBindingNoChanges (core.es5.js:8775)
    at checkNoChangesNodeInline (core.es5.js:12329)
    at checkNoChangesNode (core.es5.js:12303)
    at debugCheckNoChangesNode (core.es5.js:12922)
    at debugCheckDirectivesFn (core.es5.js:12824)
    at Object.View_PageListComponent_0.co [as updateDirectives] (PageListComponent.html:23)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12806)
    at checkNoChangesView (core.es5.js:12123)
    at callViewAction (core.es5.js:12487)