Home > Net >  how to cast json to array in angular
how to cast json to array in angular

Time:10-16

I have file1.ts which has a variable menuGroups

 menuGroups= Array();

i populate menuGroups with data so it looks something like this

menuGroups

i store this in localstorage : localStorage.setItem("menuGroups", JSON.stringify(this.menuGroups));

now in file2.ts, i want to assign above localstorage value to an array variable at class level. how to achieve it?

basically , in file2.html, i want to loop through the array menuGroups variable using ngFor.

i tried this in file2.ts but getting error

file2.ts

CodePudding user response:

  menuGroups: any[] = [];

  populateNavBar() {
    this.menuGroups = JSON.parse(localStorage.getItem('menuGroups')) || [];
  }

Working ex

CodePudding user response:

If you try to change

menuGroups: any;

Show run example stackblitz here.

  • Related