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.
CodePudding user response:
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
});
CodePudding user response:
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)">