How can I remove an array value by clicking on the typescript checkbox

Asked

Viewed 190 times

1

I have a checkbox that when clicked makes a push in an array of name perm_telas, but when I select again a check already selected it is not removing correctly the value of the array.

I tried something like:

  @ViewChildren('myItem') item; //Aqui é meu check
  perm_telas = []; //Aqui é meu array

  OnCheckboxSelect(id, event) { //Caso ocorra um check na tela, adiciona para o array perm_telas o id daquela tela.
    if (event.target.checked === true) {
      this.perm_telas.push(id);
      console.log(this.perm_telas);
    }
    if (event.target.checked === false) {//Caso clique em um já checado, retira aquele id do.
      this.perm_telas = this.perm_telas.filter((item) => id !== id);
    }
  }

The insertion is taking place correctly, I believe there is something wrong in my logic of removing from the array.

  • The condition enters the second if?

  • Yes, the problem is in implementing the remove

  • Pedro, this only works when the array is of objects. This code worked when my array was composed of ({id: id}) but I had to switch only to a numeric array, so this function no longer works for me

  • whereas the item is a numerical value, and id also... this.perm_telas.filter((item) => item !== id)

1 answer

1


When I want to remove a particular item from an object I do so:

Object

var array = ['A', 'B', 'F', 1, 2, 3, 5];

Look for 'F' inside the object. It will return your index.

var index = array.indexOf('F');

If you find the value, remove.

if (index > -1) {
  array.splice(index, 1);
}

Where index is the position and 1 is the amount of items you want to remove, in case one.


In your case it would be so:

var index = this.perm_telas.indexOf(id);

if (index > -1) {
    this.perm_telas.splice(index, 1);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.