I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail.
<div class="grp-input">
<label class="input-title">Member Search</label>
<input type="text" (keyup)="onSearchMember()" [(ngModel)]="memberName" class="form-control field-font" placeholder="Enter Member Name">
</div>
<div class="members-div d-flex flex-row col-lg-6" *ngFor="let member of memberData">
<div class="member-checkbox">
<input class="checkbox checkmark" (change)="selectMember(member,$event)" type="checkbox" name="cb" id="cb1">
</div>
<div>
<img class="member-img" [src]="img" alt="">
</div>
</div>
typescript code
memberData: Array<any> = [];
selectedMembers: Array<any> = [];
selectMember(member, e) {
if (e.target.checked) {
if (this.selectedMembers.length == 0) {
this.selectedMembers.push(member);
}
else if (this.selectedMembers.length > 0) {
const index = this.selectedMembers.indexOf(member.email);
if (index > -1) {
this.selectedMembers.splice(index, 1);
}
else if(index==-1)
{
this.selectedMembers.push(member);
}
}
}
else {
const index = this.selectedMembers.indexOf(member);
this.selectedMembers.splice(index, 1);
}
console.log("selected members",this.selectedMembers);
}
onSearchMember() {
var param;
if (this.memberName) {
param = {
"pageNo": 0,
"pageSize": 6,
"name": this.memberName
};
} else {
param = {
"pageNo": 0,
"pageSize": 4,
"name": ""
};
}
this.quoteService.get(constants.searchMember, param).subscribe(result => {
if (result != "") {
console.log(result);
this.memberData=result;
}
else {
//swal.fire(result.status, result.msg, 'warning');
}
}, error => {
swal.fire(error.status, 'Opps!Something went wrong.', 'warning');
});
}
I have encountered an issue where after searching for a member, clearing the search input field, and then selecting the same existing item again, the array treats it as a non-existing element and pushes it. It's quite frustrating. Can anyone provide some assistance with this problem? If more explanation is needed, please let me know.