How to pass values from a list in Ionic3

Asked

Viewed 502 times

0

Talk guys, I’m breaking my head with something "presently" simple, more not so much... I have a simple json with id and name, with approximately 25 records, I have to take only the records selected by the user to generate a new screen as selected items, I’m doing it this way:

<ion-list>
  <ion-list-header>
    Disciplinas
  </ion-list-header>

  <ion-item *ngFor="let dsc of disciplinas">
    <ion-label>{{ dsc.disciplina }}</ion-label>
    <ion-toggle (ngModel)="slcDisc[dsc]" checked="false"></ion-toggle>
  </ion-item>
</ion-list>

In the controller when I view iten slcDisc[] it gives as a Undefined, my question is how to take these values from the controller side!?

  • can provide the controller code?

  • That’s what I’m trying to do on the controller and I’m not getting it! When I submit the form, I am checking the other fields with the console.log() and they are coming right, when I display the selected items in the toogle gives as Undefined!

1 answer

0

I did it a little differently. I don’t know if I made it too complicated, I mean, if there’s a simpler way to do it, but it works. The benefit here is that it is not necessary to go through "Submit" to have the changes in the controller.

<ion-list>
    <ion-list-header>
      Disciplinas
    </ion-list-header>

    <ion-item *ngFor="let dsc of disciplinas">
      <ion-label>{{ dsc.disciplina }}</ion-label>
      <ion-toggle (ngModel)="slcDisc[dsc]" checked="false" (ionChange)="mudou(dsc.disciplina)"></ion-toggle>
    </ion-item>
  </ion-list>

  <button (click)="teste()"> Final</button>


import { Component } from "@angular/core";

@Component({
    selector: 'teste-tog',
    templateUrl: 'teste-tog.component.html',
  })
export class TestTogComponent {

    disciplinas: Array<{disciplina: string}> = new Array<{disciplina: string}>();
    slcDisc: Array<{disciplina: string}> = new Array<{disciplina: string}>();

    constructor(){
        this.disciplinas.push({disciplina: 'portugues'}, {disciplina: 'matematica'}, {disciplina: 'geografia'});        
    }

    teste(){
        console.log(this.slcDisc);
    }

    mudou(disciplina: string){
        let indice = this.slcDisc.findIndex( (v) => {
            return v.disciplina == disciplina
        })
console.log(indice + ' ' + disciplina);
        if ( indice == -1 )
            this.slcDisc.push({disciplina: disciplina})
        else
            this.slcDisc.splice(indice, 1);

    }
}

I only passed the discipline property for the method to change but vc tb can pass the entire dsc object. It would only be necessary to change the method signature.

Browser other questions tagged

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