1

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!

kcrisman
  • 4,374
  • 20
  • 41

1 Answers1

1

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.

Imdad Ali
  • 727
  • 1
  • 8
  • 18
  • So, in principle this works. (I just put it in the class definition.) But ... I don't understand why `selected="true"` doesn't work - and apparently is even overridden by this quantity. And why don't I have to do it for the `ion-input` item? Is there *any* reliable documentation about this sort of thing? – kcrisman Feb 13 '18 at 20:51
  • 1
    E.g. even https://ionicframework.com/docs/api/components/select/Select/ does not make it 100% obvious, though it is consistent with this answer, so I'll accept it. – kcrisman Feb 14 '18 at 02:11