How to pass values from a list in Ionic3

0

I have a simple json with id and name, with about 25 records, I have to pick only the records selected by the user to generate a new one screen according to the selected items, I'm doing the following:

<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 the iten slcDisc [] it looks like an undefined, my question is how to get those values from the controller side!?

    
asked by anonymous 21.01.2018 / 17:14

1 answer

0

I did it a little differently. I do not know if I'm too complicated, that is, if there is a simpler way to do it, but it works. The benefit here is that it is not necessary to go through the "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 change method but you can also pass the entire dsc object. You would only need to change the signature of the method.

    
22.01.2018 / 12:26