Search code examples
angulartypescriptionic-frameworkionic3ion-select

ion-select default value not loading in typescript


I've looked at this question, this question, and this question, but none of them seem to be simple enough for what I'm looking for.

<ion-list>
  <ion-item>
    <ion-label>Select Book</ion-label>
    <ion-select [(ngModel)]="selectbook" value="Return">
      <ion-option value="Hobbit">The Hobbit</ion-option>
      <ion-option value="Fellow">The Fellowship of the Ring</ion-option>
      <ion-option value="Towers">The Two Towers</ion-option>
      <ion-option value="Return" selected="true">The Return of the King</ion-option>
    </ion-select>
  </ion-item>
</ion-list>

<ion-item>
  <ion-label>Number of Hobbits</ion-label>
  <ion-input type="number" [(ngModel)]="selecthobbits" [min]="1" [max]="150" value="1"></ion-input>
</ion-item>

Then there is a button which (in the .ts file) uses this.selecthobbits and this.selectbook. But my typescript doesn't seem to be recognizing the default (I get the usual js undefined).

I know that this isn't completely failing, because this.selecthobbits always gets the right info, and this.selectbook does once someone actually click on an option, even the default. So I could go with no default value, but that seems to sort of miss the point of having a default value.

Does anyone know which of the syntaxes I use (I have tried none, both, and each one) for getting a default value that the typescript picks up is correct, or if there is another one? Frankly, it seems like I might have to import some extra module to access this (e.g. [value] versus value?), but sifting through these haystacks is a grim prospect. Thanks in advance!


Solution

  • remove value="Return" from ion-select, and selected="true" from ion-option, in the .ts file in ionViewDidLoad or whatever life cycle your are using, write below line

    this.selectbook = 'Return';
    

    option with the value Return will be selected on initialization.