Search code examples
angularcheckboxsession-cookiessession-storage

Remove a particular element in session storage angular8


I have a list of directions namely

countryList = ["South","East","West"]

<div *ngFor="let country of countryList">

     <mat-checkbox (change)="checkBoxClicked(country, $event)">
        {{country}}
     </mat-checkbox>
</div>

shown as mat-checkbox. So when user selects a particular direction, I tried to store the same in session storage

 checkBoxClicked(list, event) {          
        if (event.checked) {
        sessionStorage.setItem("TestingSelectedPages",JSON.stringify({ 'Countries': list}));   

        }
            else {
                   //How to remove the same ???
             }

        }

For example, if the Session storage value is like this enter image description here

I mean , if I uncheck a particular element, (Say , "South"), how to remove only South from the list and keep the others in session storage.


Solution

  • You are getting list which will be consist of updated values after either you checked or unchecked the checkbox. So you can directly use the setItem method to update session storage value.

    checkBoxClicked(list, event) {          
       if (event.checked) {
         sessionStorage.setItem("TestingSelectedPages",JSON.stringify({ 'Countries': list}));   
    
       } else {
        sessionStorage.setItem("TestingSelectedPages",JSON.stringify({ 'Countries': list}));   
       }
    }