How to set default value to <ion-select> from component?


#1

I want to set checkup value from my component.

I tried:

  1. checkup = "somevalue"; // outside constructor

  2. or in constructor this.checkup = "somevalue" // there is no checkup outside constructor ( in this case I get typescript error "Property 'checkup' does not exist on type 'SettingsProfilePage')

I tried all kinds of possibilities, but none seem to work.

<ion-item>
    <ion-label>Checkup</ion-label>
    <ion-select [(ngModel)]="checkup" (ionChange)="setCheckup(checkup)" [value] = "bla">
      <ion-option *ngFor="let checkup of checkups()">{{checkup}}</ion-option>
    </ion-select>
  </ion-item>

“systemInfo”:[“Ionic Framework: 2.0.0-rc.5”,
“Ionic Native: 2.2.11”,
“Ionic App Scripts: 1.0.0”,
“Angular Core: 2.2.1”,
“Angular Compiler CLI: 2.2.1”,
“Node: 7.4.0”,
“OS Platform: macOS Sierra”]};


#2

If by “outside constructor”, you mean this:

@Component()
export class MyPage {
  checkup = "somevalue";
}

That should work. If by “outside constructor”, you mean this:

export class MyPage {
  someOtherFunkyFunction() {
    externalSource.frotz().then((foo) => {
      checkup = foo;
    });
}

Then you also need to declare the property as in the first example, and setting it to some reasonable default value with an initializer is a good idea, because the template will likely access it before your future resolves. Incidentally, you shouldn’t need to pass checkup in the ionChange handler, as you already have it in your component.


#3

The first option. But it still does not work, getting the same error message.


#4

I think your problem lies elsewhere, because this appears to work for me:

  <ion-item>
    <ion-label>Checkup</ion-label>
    <ion-select [(ngModel)]="checkup" (ionChange)="logChosen()">
      <ion-option *ngFor="let checkup of checkups()">{{checkup}}</ion-option>
    </ion-select>
  </ion-item>
export class HomePage {
  checkups(): string[] {
    return [
      "foo",
      "bar",
      "baz"
    ];
  }

  checkup: string = "bar";

  logChosen(): void {
    console.log(this.checkup);
  }
}

NgRx Store Observable usage in ngModel
#5

I know what my problem was: my “default” checkup value was different from the array of checkups. I didn’t know that it had to be one of the strings defined by checkups.


#6

Many thanks! That is very helpful!


#7

i found a solution to that…
add a AbstractControl to your [(ngModel)].

example:
in yout TS file…
placeForm: FormGroup;
placeId: AbstractControl;

constructor(){
this.placeForm.formBuilder.group({
placeId: [’’, Validators.required],
});
this.placeForm.get(‘placeId’).setValue(place.id);
}

in your html
just add this [(ngModel)]=“placeForm.placeId”