如何从Ionic Dynamic Select选项中获取ID值和NAME值

问题描述 投票:1回答:1

离子3,我已经成功实现了动态选择选项,我希望能够将选中的ID值和Name值发送给服务器

因为我只能获得ID或名称,我无法获得这两个值,请帮助,我已经尝试了JSON.parse,以及id.value和name.value,但是我很遗憾只能获得第一个值而不能同时获得两个值

 <ion-list >
    <ion-item class="list-but">
      <ion-label>Tipo de Ambiente</ion-label>
      <ion-select
        [(ngModel)]="idType"
        multiple="false"
        cancelText="Cancelar"
        okText="Ok"
      >
        <ion-option
          *ngFor="let type of type_environment"
          value="{{ type.name }}"
          value="{{ type.id }}"
          #name
          >{{ type.name }}</ion-option
        >
      </ion-select>
    </ion-item>
  </ion-list>
  <button ion-button block (click)="insert()">Salvar</button>


``public type_environment = new Array<any>();
  public idType: number = 0;
  public nameType: string = "name";
  private userData: any;`
```

insert() {
    this.userData = this.user.getUserData();

    let body = {
      name: this.nameType,
      id_type: this.idType,
      id_unity: this.navParams.get("id.unidade")
    };
    console.log("name:", this.idType);

    this.route.postData("/ambiente", body).subscribe(
      data => {
        let response = data as any;

        let ret = JSON.parse(response._body);

        if (ret.insertId) {
          this.navCtrl.popToRoot();
        } else {
          console.log(ret);
        }
      },
      error => {
        console.log(error);
angular typescript ionic-framework ionic3 ionic-native
1个回答
1
投票

你不需要在你的选择中有两个value,只需将整个对象绑定到value,即:

<ion-select [(ngModel)]="idType" cancelText="Cancelar" okText="Ok">
  <ion-option *ngFor="let type of type_environment" [value]="type">
    {{ type.name }}
  </ion-option>
</ion-select>

在此之后,您在idType中获得了对象值:

insert() { 
  // below is your chosen object and its properties
  console.log(this.idType.id, this.idType.name)
}

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.