Create a sidenav component
sidenav.component.html:
<md-sidenav-container>
<md-sidenav #sidenav mode="side">
Sidenav content
</md-sidenav>
<ng-content></ng-content>
</md-sidenav-container>
sidenav.component.ts:
@Component({
selector: 'app-sidenav',
templateUrl: './sidenav.component.html',
styleUrls: ['./sidenav.component.scss']
})
export class SidenavComponent implements OnInit {
@ViewChild('sidenav') public sidenav: MdSidenav;
constructor(private sidenavService: SidenavService) { }
ngOnInit() {
this.sidenavService.setSidenav(this.sidenav);
}
}
sidenav.service.ts:
@Injectable()
export class SidenavService {
private sidenav: MdSidenav;
public setSidenav(sidenav: MdSidenav) {
this.sidenav = sidenav;
}
public open(): Promise<MdDrawerToggleResult> {
return this.sidenav.open();
}
public close(): Promise<MdDrawerToggleResult> {
return this.sidenav.close();
}
public toggle(isOpen?: boolean): Promise<MdDrawerToggleResult> {
return this.sidenav.toggle(isOpen);
}
}
(Don't forget to add the component and the service to a module!)
In the AppComponent you can use the sidenav component like this:
<app-sidenav>
<router-outlet></router-outlet>
</app-sidenav>
The router loads the components into the router-outlet
. The router-outlet
element will be placed inside the <ng-content></ng-content>
(see sidenav.component.html).
The sidenav service enables you to control the sidenav component from every component of your application.
Usage of sidenav service in header component
Inject the service inside the header component:
constructor(private sidenavService: SidenavService) { }
Create method to toggle the sidenav:
toggleSidenav() {
this.sidenavService.toggle();
}
And in the markup you can use a button like this:
<button (click)="toggleSidenav()">Toggle sidenav</button>
See small demo here:
https://stackblitz.com/edit/angular-material-kcszgq
<md-sidenav-container>
in your root component and use<router-outlet>
for showing dynamic content – wolverine