2

How can I remove the value from array when I uncheck the checkbox?

html

<input type="checkbox" id="saveUserNameCheckBox" (change)="selChk(member.id)"  [checked]="false">

component

selChk(val) {

   if (this.id.indexOf(val) == -1) {
    this.id.push(val);
    console.log(this.id);
   }
}

2 Answers 2

6

You already found the index why not just use splice?

selChk(val) {
 var index = this.id.indexOf(val);
 if(index === -1){
   // val not found, pushing onto array
   this.id.push(val);
 }else{
   // val is found, removing from array
   this.id.splice(index,1);
 }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@SagarAhuja See the comments above. If you are using a checkbox to determine inclusion of a val in a array this would be a solution to manage that.
I have added the below which explains things more better please accept it if you feel its helpful.
3

Your HTML :

<input (change)="onCheckUser(user.user_id,$event)" type="checkbox">

In your Ts:

Follow_list = []; // Variable Declared 


onCheckUser(Id, event) {
  const checked = event.target.checked; // stored checked value true or false
   if (checked) {
     this.Follow_list.push({ user_id: Id }); // push the Id in array if checked
      } else {
      const index = this.Follow_list.findIndex(list => list.user_id == Id);//Find the index of stored id
      this.Follow_list.splice(index, 1); // Then remove
    }
 }

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.