How to display and hide Toogle inside ngfor correctly?

Asked

Viewed 78 times

1

inserir a descrição da imagem aqui

listNotas() {
    
    this.service.getList(this.idAluno).subscribe(
      data => {
        this.error = data.error;
        this.list = data.message;        
        console.log(this.list);        
      },
      err => console.log(err)
    );
  }

status:Boolean=false;
  myToggle(i){
    this.status[i] = true;
    console.log(this.status[i]);    
  }
<div *ngFor="let data of list; let i = index">
    <span>
      {{data.aula}}
      <ion-toggle (click)="myToggle(i)"></ion-toggle>
    </span>
    <span *ngIf="status == true">
      {{data.nome}}
    </span>
  </div>

  • 1

    not missing accessing the status variable[i]? in if

  • 1

    What is the layout of the returned json?

  • 1

    @Virgilionovic, I edited the question and included an image with json returned

  • @Henriquemendessilveirarodri has the status field is by this field???

  • yes, but the toogle function is boolean and I can’t use this field to run individually, inside ngFor...

2 answers

1

The best way to do that would be:

First map to list for each element to have a status as false

array = array.map(obj = > { obj.status=false; return obj; }) 

Then your toggle function can be like this:

myToggle(element){
  element.active = !element.active;    
}

finally in html

<div *ngFor="let data of list">
    <span>
      {{data.aula}}
      <ion-toggle (click)="myToggle(data)"></ion-toggle>
    </span>
    <span *ngIf="data.status == true">
      {{data.nome}}
    </span>
  </div>
  • Eduardo, I edited the question and added the function I call the back-end list, the mapping I would do in this function?

  • 1

    that within the subscribe

  • How would this mapping function look? I’m not able to do it, perhaps because it’s typescritp...

0

I managed to solve and I will leave the solution posted here:

status:Boolean=false;
  myToggle(data){
    if(data.status === 1){
      data.status = 0;
    }else{
      data.status = 1;
    }    
    console.log(data.status)    
  }
<div *ngFor="let data of list">
    <span>
      {{data.aula}} - {{data.status}}
      <button ion-button (click)="myToggle(data)">mostrar</button>
    </span>
    <span *ngIf="data.status == 0">
      {{data.aula}}
    </span>
  </div>
for some reason the button <ion-toggle> didn’t work...

Browser other questions tagged

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