17

I am new to Ionic 2, I read the Ionic 2 Documentation over and thought this code would work. Its supposed to give back the current select value when it's changed and print it to console.

page.html

<ion-select #C ionChange="onChange(C.value)"> 
                    <ion-option value="a">A</ion-option>
                    <ion-option value="b">B</ion-option>
</ion-select>

page.ts

public CValue:String;
onChange(CValue) {
     console.log(CValue);
}

However the console isn't giving out anything related to this. Did I miss something in the binding?

sebaferreras
  • 44,206
  • 11
  • 116
  • 134
CMA
  • 287
  • 1
  • 2
  • 11

5 Answers5

40

Instead of

<ion-select #C ionChange="onChange(C.value)"> 
  ...
</ion-select>

Since ionChange is an event (and not a simple attribute) you need to do it like this:

<ion-select #C (ionChange)="onChange(C.value)">
  ...
</ion-select>
sebaferreras
  • 44,206
  • 11
  • 116
  • 134
3

Instead of doing it this way

<ion-select #C (ionChange)="onChange(C.value)">
  ...
</ion-select>

you can also pass "$event" to get the value

<ion-select #C (ionChange)="onChange($event)">
  ...
</ion-select>
Pang
  • 9,564
  • 146
  • 81
  • 122
0

For Ionic 4 use

<ion-select [(ngModel)]="c.value" (ngModelChange)="myFun(c.value)">
...
</ion-select>
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285
0

Use ionChange in Ionic 4 as per docs

<ion-select formControlName="item" (ionChange)="saveSettings()"><ion-select>

Make sure you include the emitEvent: false property into the options of patching to stop an initial population of data from triggering the ionChange event.

this.settingsForm.patchValue(data, {emitEvent: false, onlySelf: true})

As of writing this EDIT - ion-select is the only element it seems that fires upon patching the options, so you can end up with a double up of saving at initialisation. Stop this by setting a boolean globally that your save function looks for to denote whether or not initialisation has completed. Remember, you can help Ionic along where you need to! Frameworks are just there to help, not do it all! :D Ie:

await this.settings$.subscribe(async data => {
  if(this.initialLoading == 0) {
    console.log('Subscription data initialising...');
    await this.settingsForm.patchValue(data, {
      onlySelf:true,
      emitEvent:false
    });
    this.initialLoading = 1;
  } else {
    console.log('Settings were altered.');
  }
});

async saveSettings() {
  if(this.initialLoading == 1) {
    // your code
  }
}
Grant
  • 5,709
  • 2
  • 38
  • 50
0

In your template

<ion-label>Priority</ion-label>
   <ion-select placeholder="Select"  [(ngModel)]="pvalue" (ionChange)="getValue()">
    <ion-option value="a">A</ion-option>
    <ion-option value="b">B</ion-option>
 </ion-select>

In your Component.ts File

pvalue:any;
getValue(){
console.log(this.pvalue);
// the value will be displayed
}