lundi 29 mars 2021

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

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="" [value]="p.id" (change)="getEmployeeId($event,p.id)">
              </td>
              <td>
                 
              </td>
              <td>
                
              </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;
}



Aucun commentaire:

Enregistrer un commentaire