Polo
Polo

Reputation: 35

Angular mat-sidenav with route

I want to implement a page like Ryanair's checkout www.ryanair.com/es/es/booking/extras (but first you have to select a flight), that when you click a button, the route changes for example to .../extras/bags and opens a sidenav with the bags options, without changing the main page.

Also if you add /bags to the route mannually, the sidenav still opening.

I have all the different elements for the sidenav ok, but I don't know how to link them with the route.

I've tried using an extra <router-outlet name="sidenav"></router-outlet> inside of sidenav, but I can't open it automatically

Upvotes: 0

Views: 1718

Answers (1)

florentine
florentine

Reputation: 657

Assuming your sidenav is inside another component, let's call it MainComponent, then the template for MainComponent would look something like:

<div>Home Page</div>
<button>Hello</button>
<mat-sidenav #bagsSidenav> ... </mat-sidenav>

First you need to set up routing in your app module or routing file. It should look something like this:

const routes: Routes = [
    { path: 'main/:openSidenav', component: MainComponent},
];

The :openSidenav part of the route basically indicates that if the user types in the route to be www.mywebsite.com/main/bags, then "bags" is the value passed into the openSidenav parameter.

Then you need to inject the Angular router to MainComponent in the constructor. Then you can subscribe to the route params to check if the path includes bags, then open the sidenav:

@ViewChild('bagsSidenav') public bagsSidenav: MdSidenav;
...

constructor(private router: Router) { }

ngOnInit() {
    this.route.params.subscribe((params) => {
         if (params.openSidenav === 'bags') {
             bagsSidenav.open();
         }
    }
}

Upvotes: 1

Related Questions