How to keep state of the checkbox after the reload the page in angular 9?

1.6k Views Asked by At

I am trying to check the multiple checkboxes, when the page reloads, the state is restored to default (unchecked) and I've been buzzing my head with this. by the way I stored the checked value in the local storage but I do not know how to map it to the HTML checkbox for checked when the page reloads. please help me.

.html

<tbody>
            <tr *ngFor="let p of pmDetails1">
              <td>
                <input type="checkbox" name="{{p.id}}" [value]="p.id" (change)="getEmployeeId($event,p.id)">
              </td>
              <td>
                {{p.firstName}} {{p.lastName}}
              </td>
              <td>
                {{p.jobTitle.jobTitleName}}
              </td>

            </tr>
          </tbody>

.ts

ngOnInit() {
this.userService.getAllUsers().subscribe((x: IEmployee[]) => {
    this.pmDetails1 = x;
});

    this.selectedItem = new Array<number>();
    this.selectedEmployee = new Array<number>();
    console.log("localStorage", localStorage.getItem("selected"));
    this.selectedItem = JSON.parse(localStorage.getItem("selected"));
  }

//onSaveEmployee is a function for the button to the confirm that I checked,
 onSaveEmployee() {
    localStorage.setItem("selected",JSON.stringify(this.selectedEmployee));
  }
 getEmployeeId(e:any,id:string){
    if(e.target.checked){
      this.selectedEmployee .push(id);
   }
 else{
      this.selectedEmployee = this.selectedEmployee.filter(m => m!=id);
  }
 }

IEmployee interface

export interface IEmployee {
id: number;
firstName: string;
jobTitle: any;
lastName: String;
}
1

There are 1 best solutions below

0
Gimsara Kulathunga On

Finaly I found a way to do it. its like this.

.html

<tbody>
        <tr *ngFor="let p of pmDetails1">
          <td>
            <input type="checkbox" name="{{p.id}}" [value]="p.id (change)="getEmployeeId($event,p.id)" [checked]="isChecked(p.id)"/>
          </td>
          <td>
            {{p.firstName}} {{p.lastName}}
          </td>
          <td>
            {{p.jobTitle.jobTitleName}}
          </td>

        </tr>
      </tbody>

.ts

ngOnInit() {
this.userService.getAllUsers().subscribe((x: IEmployee[]) => {
  this.pmDetails1 = x;
});
if(localStorage.getItem("selected")){
  this.selectedEmployee = JSON.parse(localStorage.getItem("selected")); 
 }   
}
 // to save checked value 
onSaveEmployee() {
   localStorage.setItem("selected",JSON.stringify(this.selectedEmployee));
   this.dialogRef.close(this.selectedEmployee);
   this.selectedEmployee = [];
}
getEmployeeId(e:any,id:string){
   if(e.target.checked){
      this.selectedEmployee .push(id);
   }
   else{
      this.selectedEmployee = this.selectedEmployee.filter(m => m!=id);
   }
}
isChecked(id:number){
  for (let index = 0; index < this.selectedEmployee.length; index++) {
    if(id == this.selectedEmployee[index]){
      return true;
   }
 }
 return false;
}