0

I have this checkbox

<div *ngFor="let user of userList">
 {{ userList.Name }}
 <input type="checkbox" (change)="selectUser($event,user)">
</div>

selectUser(event,user)
    { 
      if (event.target.checked) {
        const userDetails = {
          userID: user.UserID,
          Name:Name ,
       };
        this.tempLists.push(userDetails); 
      }
      else
      {
        this.tempLists= this.tempLists.filter(function(obj) {
          return obj.userID !== user.UserID;
        });
      }
    }

in this method I'm adding the selected user to the array, but i want that if id is present in the array then when reloading the content where checkbox is present, the checkbox should be selected if that particular id is present in the array.

2 Answers 2

1

You need to merge the userList and the tempLists in order to put a property checked on userList and then just add [checked]="user.checked"

The merge part:

userList.map(u =>{
  const potentialTempLists = tempLists.find(t => t.UserID === u.UserID)
  return potentialTempLists ? {...u, checked: true} : u
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks can you pls add more detail how will i merge
Yes but I need more context could you print the entire component? Basically when you generate the userList at the Init time you will just loop on it: ``` userList.map(u =>{ const potentialTempLists = tempLists.find(t => t.UserID === u.UserID) return potentialTempLists ? {...u, checked: true} : u }); ```
0

You can create a function that will check if user is there in the temp list and based on that you can mark checkbox as checked so in you ts file

isChecked(user){
    return this.tempLists.some(u=> u.userID==user.UserID);
}

Then on UI user this function to see if user is checked or not

<input type="checkbox" [checked]="isChecked(user)" (change)="selectUser($event,user)">

Working demo

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.