I have a sidenav that I would like to open from a different component. I created a service for this, since it's not a parent/child relation, but I keep getting the nav back as undefined. What am I doing wrong?
This is the service:
import {Injectable} from '@angular/core';
import {MdSidenav, MdSidenavToggleResult} from "@angular/material";
@Injectable()
export class SidenavService {
private sidenav: MdSidenav;
public setSidenav(sidenav: MdSidenav) {
this.sidenav = sidenav;
}
public open(): Promise<MdSidenavToggleResult> {
return this.sidenav.open();
}
public toggle(isOpen?: boolean): Promise<MdSidenavToggleResult> {
return this.sidenav.toggle(isOpen);
}
constructor() {
}
}
this is html of InstellingenComponent with the sidenav (I deleted some of the content so It's more readable):
<md-sidenav #sidenav align="end" mode="side" opened="true">
<div>
<h3>Weergave aanpasssen</h3>
<section class="instellingen">
<h3>Kleuren</h3>
</form>
</section>
</div>
</md-sidenav>
In another component I have:
export class AppComponent implements OnInit {
constructor(private sidenavService: SidenavService) {
}
ngOnInit(): void {
}
public toggleSidenav() {
this.sidenavService
.toggle()
.then(() => {
});
} }
and the following html:
<button md-icon-button (click)="toggleSidenav()" class="button">
<md-icon>settings</md-icon></button>
You need to set a reference to the sidenav in your sidenav service so that the service can open/close the sidenav. Otherwise, it will always be undefined
In order to do this, open the InstellingenComponent.ts
file (the component whose template has the side nav component), and make the following changes:
Add this line of code to get a reference to the side nav component in the template (Add this preferably at the top, just below the export class InstellingenComponent
statement)
@ViewChild('sidenav') public sidenav: MdSidenav;
Inside your constructor, inject the SidenavService like below (note, add it to the ones that you already might have)
public constructor(
private sidenavService: SidenavService
)
Make sure the class implements OnInit
like below.
export class InstellingenComponent implements OnInit
Finally, in your ngOnInit()
function (Add new if not already present), set the reference to the sidenav like this:
public ngOnInit(): void {
this.sidenavService
.setSidenav(this.sidenav);
}