Ionic 4:如何从脚本更新或刷新 ion-select?

Ionic 4: How to update or refresh a ion-select from script?

我在 ionic 4 和 angular 中创建了一个带有注册表单的应用程序。我想执行以下操作:

我有两个 ion-selects,一个用于国家列表,另一个用于 phone 代码列表。我正在寻找的行为是:当一个国家在 ion-select 中被 selected 时,相应的 telephone 代码必须在phone 代码离子-select.

这是我的代码:

ion-select 国家

  <ion-select  id="paisselect" formControlName="pais" (ionChange)="changeselect($event)" interface="popover">

    <ion-select-option *ngFor="let c of countries" value="{{c.cod}}">{{c.name}}</ion-select-option>

 </ion-select>

ion-select 用于 phone 代码

    <ion-select formControlName="phonecode" placeholder="Cod." interface="popover">

    <ion-select-option *ngFor="let c of codetele" value="{{c.code}}" selected="{{codigoselected == c.code}}">{{c.code}}</ion-select-option>

</ion-select>

这是我用来更新 phone 代码离子的函数-select

changeselect($event){
    console.log($event.target.value) ;
    let item1 = this.countries.find(i => i.cod === $event.target.value);
    console.log(item1) ;
    this.codigoselected = item1.code;
    console.log(this.codigoselected) ;
}

我正在使用变量 "codigoselected" 来确定 select 编辑了哪个国家/地区。为此,在 ion-select-选项中,我使用一个条件来更改选项的 selected 状态,如下所示:

<ion-select-option *ngFor="let c of codetele" value="{{c.code}}" selected="{{codigoselected == c.code}}">{{c.code}}</ion-select-option>

当前行为是这样的:

我select访问了一个国家:

但是 phone 代码的 ion-select 似乎没有更新

但是当我点击字段时,具体代码是selected

我需要在选项 select 下执行 clic 以便刷新字段:

那么,如何让 phone 代码字段在界面中自动更新而无需用户点击?

试试这个,将 phone 代码 select 元素传递给您的 changeselect(event, phoneCodeSelect) 函数。

<ion-select  id="paisselect" formControlName="pais" (ionChange)="changeselect($event, phoneCodeSelect)" interface="popover">

    <ion-select-option *ngFor="let c of countries" value="{{c.cod}}">{{c.name}}</ion-select-option>

 </ion-select>

#phoneCodeSelect 添加到您的 phone 代码 select 元素。

<ion-select #phoneCodeSelect formControlName="phonecode" placeholder="Cod." interface="popover">

    <ion-select-option *ngFor="let c of codetele" value="{{c.code}}" selected="{{codigoselected == c.code}}">{{c.code}}</ion-select-option>

</ion-select>

然后在您的函数中手动更改 select 元素的值,同时更新 phone 代码表单控件值。

changeselect($event, phoneCodeSelect){
    console.log($event.target.value) ;
    let item1 = this.countries.find(i => i.cod === $event.target.value);
    console.log(item1) ;
    this.yourFormGroup.value.phonecode = item1.code; // change yourFormGroup to what your variable's name is 
    phoneCodeSelect.value = item1.code;
}