2020-02-23 ionic-select 控件显示默认值问

2020-02-23  本文已影响0人  FredWorks

问题描述:

假设显示代码如下:

    <ion-item>
      <ion-label class="primary">支出账户</ion-label>
      <ion-select [(ngModel)]="fromFaBookId" interface="popover">
        <ion-select-option *ngFor="let item of allFaBooks" value="{{item.id}}">{{item.name}}</ion-select-option>
      </ion-select>
    </ion-item> 

这段代码,当模型的 fromFaBookId 属性有默认值时,会自动匹配到该值在下拉选项中对应的显示文本并显示出来。

但下面这段代码几乎一样,却没有显示默认值:

    <ion-item>
      <ion-label class="primary">交易类型</ion-label>
      <ion-select [(ngModel)]="tradeType" interface="popover">
        <ion-select-option *ngFor="let item of allTradeTypes" value="{{item.id}}">{{item.name}}</ion-select-option>
      </ion-select>
    </ion-item> 

这段代码,在确保模型的 tradeType 属性有默认值时,界面却没有显示该值在下拉选项中对应的显示文本。

解决方案

在ionic的官方文档中,找到 ion-select 控件有属性 selectedText,其描述如下:

Description The text to display instead of the selected option's value.
Attribute selected-text
Type null | string | undefined

给上述代码添加 selectedText 属性后,这正常显示默认值了:

    <ion-item>
      <ion-label class="primary">交易类型</ion-label>
      <ion-select [(ngModel)]="tradeType" selectedText="{{fetchTradeTypeLabel(tradeType)}}" interface="popover">
        <ion-select-option *ngFor="let item of allTradeTypes" value="{{item.id}}">{{item.name}}</ion-select-option>
      </ion-select>
    </ion-item> 

重点是这行代码: selectedText="{{fetchTradeTypeLabel(tradeType)}}"。其中,fetchTradeTypeLabel(tradeType: string)是一个获取交易类型对应显示文本的函数。

遗留问题

虽然现在已经显示默认值了,但是仔细观察,发现点开下拉框后,默认值对应的选项并未被选中。
虽然经过验证,即使不手动选中对应选项,提交数据到服务器后,属性 tradeType 对应的数据(默认值)仍然是读取到了,但是默认值对应的选项没有显示为被选中,仍然是一个瑕疵。

上一篇下一篇

猜你喜欢

热点阅读