I have the following Angular component (simplified for question):
<md-sidenav-container fxFlex>
<div fxFlex class="app-content">
This is the content
</div>
<button *ngIf="newsbar.opened" type="button" (click)="closeBar(newsbar)">Close</button>
<button *ngIf="!newsbar.opened" type="button" (click)="openBar(newsbar)">Open</button>
<md-sidenav #newsbar mode="side" [opened]="showNewsBar()" align="end" class="app-news-bar">
<app-news-bar></app-news-bar>
</md-sidenav>
</md-sidenav-container>
And the following is the function which dictates whether the newsbar is open or not (based on the window width).
showNewsBar() {
const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (width >= 1280) {
return true;
} else {
return false;
}
}
When running the app, everything works as expected. When the window is smaller or becomes smaller than 1280px, the sidebar closes and the "Open" button is shown. When the window is larger or becomes larger than 1280px, the sidebar opens and the "Close" button is shown. But, whenever the window is resized to trigger a change in the function showNewsBar()
, I get an error.
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.
When I resize the window so it becomes larger and the newsbar opens, Previous value: 'false'. Current value: 'true'.
The line that gives me the error are the buttons. For some reason, Angular doesn't like that I'm binding the *ngIf directives to the local MdSidenav reference's "opened" property.
Again, everything works as expected. Nothing wrong with the functionality. So why does this error occur? And is there a way to fix it?