0

I am trying to retain checkbox checked even after a page refresh, trying to store the checked values in local storage but I don't know how to retain the checkbox checked in angular 7

.html

<div *ngFor="let item of cityList; let i = index">
<label [for]="item+i"> {{item}} </label>
<input type="checkbox"class="save-cb-state" value="{{item.checked}}" [checked]="item.Checked" [id]="item+i" [name]="item" [(ngModel)]="item.Checked" (ngModelChange)="getCheckboxValues($event,item)">
</div>

.ts

getCheckboxValues(event, data) {

  let index = this.selectedCity.findIndex(x => x.order==data);
  if (event) {
    let obj = data;

    this.selectedCity.push(obj);

    let some;
    if(localStorage.getItem('cheked') === null ){
      some = [];
    } else{
      some = JSON.parse(localStorage.getItem('checked'));

    }
    some.push(this.selectedCity)
    localStorage.setItem('checked',JSON.stringify(some));
    localStorage.CBState = JSON.stringify(some);
  }
  else {

    this.selectedCity.splice(index, 1);
    localStorage.removeItem('checked');
    console.log(checked,'this got uncheked') 

  }
  // console.log(this.selectedCity);
}
6
  • Can you please redo your description? Maybe it is just my since English is not my first language but I do not understand exactly what do you want to do. Commented Mar 3, 2020 at 18:45
  • @distante please review once, hope I made it clear, Commented Mar 3, 2020 at 18:51
  • In your html code you have item.checked and item.Checked is it a typo? Commented Mar 3, 2020 at 18:52
  • in a nut shell, I am trying to save checkbox, checked values Commented Mar 3, 2020 at 18:52
  • Also what data you have in your cityList array? Commented Mar 3, 2020 at 18:53

1 Answer 1

1

When saving to local storage, there's no need to try and insert a selected value into the existing value - just write whatever you have to local storage each time the state changes.

The approach I would take:

  1. Get city names
  2. Retrieve selected cities from local storage and apply checked value
  3. On checkbox change save current selected cities to local storage

Step 1 - loading the cities

You are retrieving an array of cities from your API. I will assume a string array for the purposes of this answer to keep it simple, but it's trivial to convert to using objects.

Once you have received your cities, you will then need to retrieve selected cities from local storage. I am going to store a comma-separated list of city names for this example, but you could persist whatever unique values you wish.

component.ts

cityList: { name: string, checked: boolean }[];

ngOnInit() {
  this.getCities().subscribe((cities: string[]) => {
    const selected: string[] = [];

    const stored: string = localStorage.getItem('cities');    
    if (stored) {
      // split comma-separated string into array of city names
      selected.push(...stored.split(','));      
    }

    // map retrieved cities to our model, 
    // applying checked where we find a city in local storage
    this.cityList = cities.map(name => ({
      name: name,
      checked: selected.includes(name)
    }));
  });    
}

Your HTML has a few unecessary things in it. You don't need to manage the checkbox checked status if you are using [(ngModel)].

component.html

<div *ngFor="let city of cityList; let i = index">
  <label>
    {{city.name}}
    <input type="checkbox" [(ngModel)]="city.checked" (ngModelChange)="saveCities()" />
  </label>  
</div>

Step 2 - saving the cities

All fairly simple stuff. The saveCities() function in the component.ts is going to serialize the selected city names to local storage every time a checkbox is updated.

component.ts

saveCities() {
  const selected: string[] = this.cityList
    .filter(x => x.checked)
    .map(x => x.name);

  const serialized: string = selected.join(',');
  localStorage.setItem('cities', serialized)
}

DEMO: https://stackblitz.com/edit/angular-rww9fr

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.