Search code examples
angularangular-materialmat-sidenav

Angular Material sidenav with submenu does not push properly when scrollbar visible


I am using Angular Material sidenav and my menu has a sub menu. When I open the sub menu a scrollbar appears making the sidenav slightly larger and it covers some of the main content.

See this Stackblitz https://stackblitz.com/edit/angular-raedvz, expand the sub menu and you will see the behavior.


Solution

  • By default, Angular Material will only resize the container on nav.open, window.resize or on a mode change of the nav. You either have to trigger the resize of the container yourself or you could use the built in option autosize. But they tell you to use it at your own risk because it could cause performance issues.

    <mat-sidenav-container class="example-container" *ngIf="shouldRun" autosize> Example on your stackblitz: https://angular-wsvjf8.stackblitz.io

    I tested is in your example provided and it does work for me. If you get performance issues cause your app is doing lots more than just the example (obviously) you might have to trigger the resize yourself on your toggleMenu method.

    https://material.angular.io/components/sidenav/overview#resizing-an-open-sidenav


    Update on your comment:

    Im not sure whether this is the correct way or not. Based on what I can find in the code for the autosize option. What they do is check the margins every change detection cycle, which is why it could cause performance issues using the autosize option. Afterwards, they call the private function _updateContentMargins and correct the margins of the container.

    You could use a ViewChild and access the MatSidenavContainer and call that function in your toggleMenu. But since the _updateContentMargins function itself is private, I wouldn't use it. Personally I can't think of another way of doing this.

    Here's a working example of calling _updateContentMargins within your toggleMenu: https://stackblitz.com/edit/angular-segnwt

    I'm using setTimeout here as _ngZone of MatSidenavContainer was also made private now.