I am wondering how to get value from local storage for a dropdown and I am very stuck on it and tried some related code present in a stack overflow but no luck!
my dropdown
<p-dropdown *ngIf="languages.length"
[options]="languages"
[(ngModel)]="selectedLanguage.name" optionLabel="name"
(onChange)="modo(selectedLanguage.mod)"></p-dropdown>
Saving selected language to local storage that works fine
onChangeDropDown() {
localStorage.setItem('selectedLanguage', this.selectedLanguage.name);
}
getting languages from a JSON file
// its not working
this.selectedLanguage = localStorage.getItem('selectedLanguage');
//JSON data
this.httpClient.get<any>('../assets/data/languages.json')
.toPromise()
.then(res => res.data as any[])
.then(data => this.languages = data);
Isn't it because you are saving this.selectedLanguage.name and loading it as this.selectedLanguage so you have the name in this variable then?
You should search languages by name with the value from local storage.
this.selectedLanguage = languages.find((l) => l.name === localStorage.getItem('selectedLanguage'))