I have a mat-button-toggle group and when I check a button on it, it stores a value in localStore.
And I want to get the value stored in the localStorage and after a page refresh keep the mat-button-toggle checked in fonction of the stored value in the localStorage.
Here is my component.html :
<p>
<mat-button-toggle-group>
<mat-button-toggle class="grille" (click)="callSwitchGrille()">
<app-icon nomIcon="grille" [stroke]=true [size]="'1.8'"></app-icon> Grille
</mat-button-toggle>
<mat-button-toggle class="tableau" (click)="callSwitchTableau()">
<app-icon nomIcon="tableau" [stroke]=true [size]="'1.8'"></app-icon> Tableau
</mat-button-toggle>
</mat-button-toggle-group>
</p>
So I can switch between "Grille" and "Tableau" and so I store "grille" or "tableau" in the localStorage and I'd like that if "grille" is stored the button stays checked on "Grille".
Here is my component.ts where I store the data :
constructor(private localStorageService : LocalStorageService) { }
setDisplayMode(mode:DisplayMode){
this.displayMode=mode;
this.displayModeChanged.emit(this.displayMode);
localStorage.setItem('displayModeKey', this.displayMode)
}
callSwitchGrille(){
this.setDisplayMode(DisplayMode.GRILLE)
}
callSwitchTableau(){
this.setDisplayMode(DisplayMode.TABLEAU)
}
}
I tried a lot of different things and it's not working as I want, so if you could help me I would really appreciate.
Thank you very much
I created a class just to explain the whole stuff but in your case, it could be an existing component where you are already working on
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-experiments",
templateUrl: "./experiments.component.html",
styleUrls: ["./experiments.component.scss"],
})
export class ExperimentsComponent implements OnInit {
displayMode: string;
constructor() {}
ngOnInit(): void {
this.displayMode = localStorage.getItem("displayModeKey");
}
setDisplayMode(mode: string) {
localStorage.setItem("displayModeKey", mode);
this.displayMode = mode;
}
}
.html file
<p>
<mat-button-toggle-group>
<mat-button-toggle
[ngClass]="{ grille: displayMode === 'grille' }"
(click)="setDisplayMode('grille')"
>
<app-icon nomIcon="grille" [stroke]="true" [size]="'1.8'"></app-icon>
Grille
</mat-button-toggle>
<mat-button-toggle
[ngClass]="{ tableau: displayMode === 'tableau' }"
(click)="setDisplayMode('tableau')"
>
<app-icon nomIcon="tableau" [stroke]="true" [size]="'1.8'"></app-icon>
Tableau
</mat-button-toggle>
</mat-button-toggle-group>
</p>
.scss or .css file
.grille {
border: 4px rgb(170, 231, 0) solid;
}
.tableau {
border: 4px #c03 solid;
}