ionic: onClick of ion-select,如何给populate/refresh选项?

Ionic: onClick of ion-select, how to populate/refresh options?

我正在尝试填充 ion-select 选项 onClick 该字段。 第一次单击 select 字段时,弹出模式为空选项。我第二次得到填充选项。

.ts

 loadLists() {
        this.car.getMakeList().then(res => {
            this.lists = res.makes;
        });
     }

.html

 <ion-item>
             <ion-label>Car Makes</ion-label>
             <ion-select (click)="loadLists()">
                 <ion-option *ngFor="let list of lists" value="{{ list.value }}">{{ list.label }}</ion-option>
             </ion-select>
        </ion-item>

ionDidViewLoad后如何填充或刷新选项? 我试过了

ApplicationRef.tick(), NgZone.run(callback), ChangeDetectorRef.detectChanges()

刷新选项弹出窗口。

但对我没有任何作用。

尝试用

替换视图加载函数
ionViewWillEnter(){
this.car.getMakeList().then(res => {
        this.lists = res.makes;
    });
}

一种方法是

  1. 禁用 select 这样点击就不会打开它
  2. 更改样式使其看起来不像未启用
  3. 处理点击 ion-item 加载选项并打开 select

请查看 working plunker 以了解实际效果!


home.html

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <!-- Handle the click on the ion-item instead of the ion-select -->
    <ion-item (click)="onOpenSelect()">
      <ion-label>Car Makes</ion-label>
        <!-- Add the disabled property to the ion-select -->
        <ion-select disabled>
          <ion-option *ngFor="let option of options" [value]="option.value">
           {{ option.label }}
          </ion-option>
        </ion-select>
      </ion-item>
  </ion-list>

</ion-content>

home.scss

page-home {
  /* Make the opacity to be 1 so it doesn't look like disabled */
  .item-select-disabled ion-label, 
  .select-disabled {
    opacity: 1 !important;
  }
}

home.ts

import { Component, ViewChild } from '@angular/core';
import { NavController, Select } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  styleUrls: [ './home.scss' ]
})
export class HomePage {

  public options = [];
  @ViewChild(Select) select: Select;

  constructor(public navCtrl: NavController) {}

  public onOpenSelect(): void {
    console.log(`Options before opening: ${this.options.length}`);

    // We need to do this because otherwise the open()
    // event won't do anything since Ionic thinks the
    // component is disabled
    this.select.disabled = false;

    // Load the new options only if needed
    if(this.options.length === 0) {
      this.options = [
          { value: 1, label: 'Option 1' },
          { value: 2, label: 'Option 2' },
          { value: 3, label: 'Option 3' },
          { value: 4, label: 'Option 4' }
      ];
    }

    // Use a timeout to give some time to Angular
    // to update the view. The amount of time is not
    // important; it's just to run the code async
    setTimeout(() => {

      // Open the select
      this.select.open();

      console.log(`Options after opening: ${this.options.length}`);
    }, 100);
  }

}