离子性:onClick of ion-select,如何填充/刷新选项?

时间:2018-09-27 08:08:34

标签: angular typescript ionic-framework ionic2 ionic3

我正在尝试在该字段的onClick中填充离子选择选项。 第一次单击选择字段时,出现空选项弹出模式。第二次我得到填充选项。

.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(回调),   ChangeDetectorRef.detectChanges()

刷新选项弹出窗口。

但是对我没有任何帮助。

2 个答案:

答案 0 :(得分:0)

尝试用

替换视图确实加载功能
ionViewWillEnter(){
this.car.getMakeList().then(res => {
        this.lists = res.makes;
    });
}

答案 1 :(得分:0)

一种方法是

  1. 禁用选择,以使点击不会将其打开
  2. 更改样式,使其看起来好像未启用
  3. 处理ion-item上的点击以加载选项并打开选择

请查看 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);
  }

}