1

我已经创建了选择,选项是从 API 加载的,问题是当我有一些之前设置的值时,现在我想在这个选择中显示这个我没有看到这个值,点击选择后可以看到标记的选项。这是为什么?我的代码。

<form [formGroup]="form">
  <ion-item class="transparent">
    <ion-select cancelText="Cancel" formControlName="type">
      <ion-select-option *ngFor="let type of types" [value]="type">{{type.name}}</ion-select-option>
    </ion-select>
  </ion-item>
</form>

ngOnInit() {
    this.form = this.fb.group({
        type: new FormControl('')
    })
    this.service.getTypes().then((types) => {
        this.types= types;
        this.form.controls['type'].setValue(this.types[0]);
    });
  }

export class Type{
  public id: number;
  public name: string;
}

选择未触及

标记值

When select is touched value is visible

请告知,是否可以显示此数据。

4

2 回答 2

0

在您的ion-select-option字段必须具有string,而不是像您尝试的对象或 Integer ,以链接它并将 Integer 值 id 解析为字符串,您可以进行类似的操作: ([value]="'type 。ID'”)

<ion-select-option *ngFor="let type of types" [value]="'type.id'">{{type.name}}</ion-select-option>
于 2020-12-09T11:57:09.353 回答
0

我在这个Stackblitz 演示中使用了几乎完全相同的东西,一切似乎都工作正常,所以你的代码中的其他地方一定有问题,而你的问题中没有显示。

随意分叉 Stackblitz 演示,看看您是否可以在那里重现该问题。

这是组件的代码:

import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormControl, FormGroup } from "@angular/forms";
import { Item } from "../../models/item.model";
import { ItemsService } from "../../services/items.service";

@Component({
  selector: "app-home",
  templateUrl: "./home.page.html",
  styleUrls: ["./home.page.scss"]
})
export class HomePage implements OnInit {
  public form: FormGroup;
  public items: Array<Item>;

  constructor(
    private formBuilder: FormBuilder,
    private itemsService: ItemsService
  ) {}

  ngOnInit() {
    this.form = this.formBuilder.group({
      item: new FormControl("")
    });

    this.itemsService.getItems().then(items => {
      this.items = items;

      // Select the second item by default
      this.form.controls["item"].setValue(this.items[1]);
    });
  }
}

这是视图的代码:

<ion-header>
  <ion-toolbar>
    <ion-title>Home</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
  <form [formGroup]="form">
    <ion-list>
      <ion-item>
        <ion-label>Item</ion-label>
        <ion-select cancelText="Cancel" formControlName="item">
          <ion-select-option *ngFor="let item of items" [value]="item">
            {{ item.name }}
          </ion-select-option>
        </ion-select>
      </ion-item>
    </ion-list>
  </form>
</ion-content>
于 2020-12-09T21:32:21.230 回答