问题
I am working on an angular project, I've implemented angular material components like the side-nav. The side-nav has ul li elements, where the links are nested and are router links not href. my question when I select a link to go to another view, I want to make a call to side nav to toggle and close. cause it always remains open
回答1:
Option 1:
You can subscribe to Router
events and close sidenav whenever router event takes place.
Code:
requires these imports:
import { Component,ViewChild, OnInit, } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { MdSidenav, MdSidenavModule } from '@angular/material';
in component class:
@ViewChild(MdSidenav) sidenav: MdSidenav;
title = 'Tour of Heroes';
constructor(private appService: AppService,
private _router: Router){
}
ngOnInit() {
this._router.events.subscribe(() => {
this.sidenav.close();
});
}
demo
Option 2:
Add a click
event to each li
to close sidenav on click.
html:
<ul class="sidenav">
<li class="sidenav__list">
<a class="sidenav__list__link " (click)="sidenav.close()" >about</a>
</li>
</ul>
demo 2
来源:https://stackoverflow.com/questions/45615414/closing-md-sidenav-when-router-link-is-selected