Function "change" with <ion-select><ion-option>

Asked

Viewed 6,590 times

7

all right? I’m struggling, I hope you can help me... I’m studying Ionic 2 a little while and thought I’d make a simple application. In Javascript I managed to do it quietly, but with Ionic does not work. It’s the onChange() method that in Ionic I believe is ionChange (by what I researched), but I can’t make it work. I want that when selecting "race"() "Humans"() the console shows a message "It worked out". Very simple, but I can’t.

HMTL:

<ion-list>
   <ion-item>
    <ion-label>Raças</ion-label>
      <ion-select id="racas" [(ngModel)]="racas" (ionChange)="teste();">
        <ion-option value="humanos">Humanos</ion-option>
        <ion-option value="anoes">Anões</ion-option>
        <ion-option value="elfos">Elfos</ion-option>
        <ion-option value="gnomos">Gnomos</ion-option>
        <ion-option value="meio-elfos">Meio-elfos</ion-option>
        <ion-option value="meio-orcs">Meio-orcs</ion-option>
        <ion-option value="halfling">Halfling</ion-option>
      </ion-select>
    </ion-item>
  </ion-list>

TS:

export class HomePage {
  public racas:string;

  teste(racas:string) {
    let x = (<HTMLInputElement>document.getElementById("racas")).value;
      if (x == "humanos") {
        console.log("Deu Certo!");
      }
  }
}

1 answer

3


Like you’re already making one Two-way binding in racas, just access it as follows:

export class HomePage {
  public racas:string;

  teste() {
      if (this.racas == "humanos") {
        console.log("Deu Certo!");
      }
  }
}

See working on plnkr

@Edit

If I wasn’t making a bind, how would I look?

If I wasn’t doing it with Two-way binding, would be as follows using the event binding:

<ion-list>
   <ion-item>
    <ion-label>Raças</ion-label>
      <ion-select (ionChange)="teste($event);">
        <ion-option value="humanos">Humanos</ion-option>
        <ion-option value="anoes">Anões</ion-option>
        <ion-option value="elfos">Elfos</ion-option>
        <ion-option value="gnomos">Gnomos</ion-option>
        <ion-option value="meio-elfos">Meio-elfos</ion-option>
        <ion-option value="meio-orcs">Meio-orcs</ion-option>
        <ion-option value="halfling">Halfling</ion-option>
      </ion-select>
    </ion-item>
  </ion-list>

HomePage.ts

export class HomePage {
  teste(racas: any) {
      console.log(racas);
  }
}
  • Marcelo, thank you so much! It worked right away! If I wasn’t making a bind, how would it look?

  • Using the event binding, added to the reply.

Browser other questions tagged

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