Search code examples
angularangular-materialrouter-outletmat-sidenav

Can I use the same Angular router-outlet in different templets based on screen size


I'm trying to make my main page have a mat-sidenav when the screen is on desktop, but use mat-toolbar when it is on tablets and mobile. I have no problem getting this done. The problem I'm running into is displaying the router-outlet. I want to have the same router-outlet used for the both layouts. I have tried numerous ways to get this done, but the result is always the mobile mat-toolbar is the one the router-outlet works on. Here are a couple snippets of what I have tried.

Try #1

app.component.html

<div fxShow.lt-md="false">
  <mat-sidenav-container class="nav-container">
    <mat-sidenav opened mode="side" class="nav-menu">Side Nav</mat-sidenav>
    <mat-sidenav-content>
      <router-outlet></router-outlet>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>

<div fxShow.gt-sm="false">
  <mat-toolbar fxLayout="row" fxLayoutAlign="center center">
    <span>Top Nav</span>
  </mat-toolbar>
  <router-outlet></router-outlet>
</div>

Try #2

Seperating out the two nav components

side-nav.component.html

<mat-sidenav-container class="nav-container">
  <mat-sidenav opened mode="side" class="nav-menu">Side Nav</mat-sidenav>
  <mat-sidenav-content>
    <router-outlet></router-outlet>
  </mat-sidenav-content>
</mat-sidenav-container>

top-nav.component.html

<mat-toolbar fxLayout="row" fxLayoutAlign="center center">
  <span>Top Nav</span>
</mat-toolbar>
<router-outlet></router-outlet>

app.component.html

<app-side-nav></app-side-nav>
<app-top-nav></app-top-nav>

Try #3

I have also tried adding the router-outlet to its own component, and replaced the router-outlet in the app.component.html.

content.component.html

<router-outlet></router-outlet>

app.component.html

<div fxShow.lt-md="false">
  <mat-sidenav-container class="nav-container">
    <mat-sidenav opened mode="side" class="nav-menu">Side Nav</mat-sidenav>
    <mat-sidenav-content>
      <router-outlet></router-outlet>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>

<div fxShow.gt-sm="false">
  <mat-toolbar>
    <span>Top Nav</span>
  </mat-toolbar>
  <app-content></app-content>
</div>

But it still only shows for the mat-toolbar still.

Is there a way to get this to work?

I know this sounds like some of the other questions, but I'm not using child routes. The same router content is displayed in the appropriate reactive design in the router-outlet.

If there is a similar question with an answer, please share the link because I haven't found it.


Solution

  • I think you have a problem with fxShow. It's hiding the element. But it's part of the DOM. That means you have two router-outlets. Try it with an *ngIf instead. With *ngIf it's not part of the DOM.