selected value in carousel

Viewed 82

i have carousel of years in my project, which selected value i have saved in my localestorage from different page, on my other page on default i want to show value i am getting from localestorage, (by default value is 3), which in this case is 5, how can i achieve that? here is my stackblitz of carousel

.html

 <carousel #myCarousel height="100%" width="120" cellsToShow="1" [lightDOM]="true" overflowCellsLimit="4">
            <div class="carousel-cell" *ngFor="let year of years">
              {{year.year}}y
            </div>
          </carousel>

.ts

if(getFromLocalStorage('data').hasOwnProperty('period')) {

    }

    console.log(this.data.period); // 5 

      years = [{
        year: 3,
        value: 3,
      },
      {
        year: 4,
        value: 4
      },
      {
        year: 5,
        value: 5
      },
      {
        year: 6,
        value: 6
      },
      {
        year: 7,
        value: 7
      },
      {
        year: 8,
        value: 8
      },
      {
        year: 9,
        value: 9
      },
      {
        year: 10,
        value: 10
      },
    ]

 get data(): any {
return JSON.parse(localStorage.getItem('data'));

}

.service

export function getFromLocalStorage<T>(storageKey: string): T {
    return JSON.parse(localStorage.getItem(storageKey));

}

1 Answers

you need to create a Storage Service, that would get/set/remove/dump/load parameters. Then assign this Service a constructor in your main ts file use something like this in your ngOnInit method

 constructor(private storage: StorageService) {
this.storage.get(AGE_VAL).then((val) => {
    if (val) {
    this.data.Age = val;
  } else {
  // some default value
   this.data.Age = this.defaultValue;
});

}

Secondly, in your carusel add an event trigger that would save the chosen value to storage.

  public onClickChooseYeats(event) {this.storage.set(AGE_VAL, event) }
Related