Ngmodel with angular checkbox

Asked

Viewed 1,717 times

1

I have a checkbox that is iterated on an ngfor:

 <div *ngFor="let tela of telas; let i = index; trackBy: getIndex" class="custom-control custom-checkbox check">
    <input type="checkbox"  [(ngModel)]=selectedIds[i] (click)="OnCheckboxSelect(tela.id, $event)" #myItem value="{{tela.id}}" id="{{tela.nome_tela}}" name="{{tela.nome_tela}}" class="custom-control-input">
    <label class="custom-control-label" for="{{tela.nome_tela}}">{{tela.nome_tela}}</label>
</div>

There is a moment when I get the array of selectedIds again to make changes, but I get the array in the following format:

[1.3.5] These are the screen ids that a user can access, but my ngModel would need to receive: [0:true, 2:true, 4:true] to bind.

I’m trying to make a repeating structure to achieve the desired result. I tried something like:

  this.selectedIds = [];
  for(let i=0;i<this.operador.tabela_perm.length;i++){
    this.selectedIds[this.operador.tabela_perm - 1] = true;
  }

But my logic is still wrong. Could someone help me?

  • The this.operador.tabela_perm is the array [1,3,5]?

  • @Renata yes, I need to transform it into the format in which ngmodel performs the bind [key: true]

2 answers

2


As I’m seeing you need that value true or false is associated with the index of the array, I suggest something like the code below, assuming the values of the this.operador.tabela_perm are always in ascending order:

let max = this.operador.tabela_perm[this.operador.tabela_perm.length-1];

this.selectedIds = [];
for(let i=0;i<max;i++){
  if(this.operador.tabela_perm.indexOf(i+1)>-1) this.selectedIds[i] = true;
  else this.selectedIds[i] = false;
}

0

Try using the array map function:

this.selectedIds.map(id=>{
   const obj={};
   obj[id-1]=true;
   return obj;
})
  • It didn’t work for me. I honestly don’t know what condition I should use to check the checkbox based on what I get from my backend. I get an array[1,3,5] which is the screen permission. I thought about doing something like [checked]=selectedId[i] == screen.id but it didn’t work.

Browser other questions tagged

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