在子级中更改父级值时,如何避免ExpressionChangedAfterItHaHasBeenCheckedError?

时间:2018-09-18 07:16:27

标签: angular

在我们的应用程序中,路由器出口位于app.component内可切换的侧边栏中。边栏的可见性由SideBarService管理。用于切换侧边栏的按钮使用*ngIf来显示显示或隐藏箭头。

<div id="sidebar" [style.width.px]="this.sideBarService.getWidth()">
    <router-outlet></router-outlet>
    <a id="sidebar-toggle-button" (click)="toggleSideBar()">
        <div *ngIf="this.sideBarService.hidden; then inactive else active"></div>
        <ng-template #active><i class="material-icons ui-icon-chevron-left"></i></ng-template>
        <ng-template #inactive><i class="material-icons ui-icon-chevron-right"></i></ng-template>
    </a>
</div>

服务:

@Injectable()
export class SideBarService{
    public width: number;
    public hidden;

    public changeWidth(width: number): void {
        this.width = width;
    }

    public getWidth(): number {
        return (this.hidden === true ? 0 : this.width);
    }

    public hide(): void {
        this.hidden = true;
    }

    public show(): void {    
        this.hidden = false;
    }
}

现在,更改sideBarService.hidden值的位置来自路由器出口中显示的组件。也许这就是为什么我不断收到以下错误的原因:

  

ExpressionChangedAfterItHasBeenCheckedError:表达式已更改   经过检查后。先前的值:'ngIf:undefined'。当前   值:“ ngIf:false”。

我相信这是因为更改是从app组件的子组件触发的。但是我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:2)

您可以使用角度ChangeDetectorRef来检查视图及其子视图。与detach结合使用可实现本地更改检测检查。

import { Component , ChangeDetectorRef } from '@angular/core';

...

constructor(private cdr:ChangeDetectorRef){}

和隐藏通话后:

this.cdr.detectChanges();