Home > Enterprise >  Angular with reactive sidenav
Angular with reactive sidenav

Time:12-24

I'm trying to create something reactive, just for learning purposes, so please ignore the project structure =).

My folder structure

1

app.component.html

<app-header></app-header>
<app-sidenav></app-sidenav>
<app-footer></app-footer>

header.component.html

<mat-toolbar color="aries-primary" >
  <button mat-icon-button (click)="toggle()">
    <mat-icon>menu</mat-icon>
  </button>
  <span>My App</span>
  <span ></span>
</mat-toolbar>
export class HeaderComponent implements OnInit {

  constructor(private toggleService: ToggleService) {
  }

  private status: boolean = false;

  public toggle(): void {
    this.status = this.toggleService.toggleStatus(this.status);
  }

  ngOnInit(): void {
  }

}

sidenav.component.html


<mat-sidenav-container>
  <mat-sidenav [(opened)]="opened" mode="side">Start</mat-sidenav>
  <mat-sidenav-content>
    <router-outlet></router-outlet>
  </mat-sidenav-content>
</mat-sidenav-container>
export class SidenavComponent implements OnInit {
  public opened: boolean = this.toggleService.getStatus();

  constructor(private toggleService: ToggleService) {
  }

  ngOnInit(): void {
  }

}

And my service

export class ToggleService {
  private status: boolean = false;
  public toggleStatus(value: boolean) {
    return this.status = !value;
  }

  public getStatus() {
    return this.status;
  }

  constructor() { }
}

When I click on the header button, there is no change in the sidenav, it is not opening and closing. As I understand it, the sidenav just calls the status (which starts with false) when the page is loaded. I would have to create something "reactive" to listen to the event. Would it be this? Now I got lost. If anyone can help, I appreciate it.

CodePudding user response:

You can't store a value in a service variable the way you are trying to do it. Every time you will call the service, this line :

private status: boolean = false;

will instantiate the variable to false.

To keep track of states, you should store values in local storage, or use a token service.

  • Related