ion-select 设置起始值

ion-select set start value

我正在尝试为 Ion-select 设置显示的初始数据。 我已经将它缩小到这个最简单的例子,尽管我在另一种情况下也有它。这里的大多数问题似乎都在使用 [ngModel],我认为我不需要它,因为我使用的是 Angular 响应式表单。 html 是:

  <form [formGroup]="userDetailsForm" (ngSubmit)="onSubmit()">

 ... some stuff
<ion-item>
  <ion-label>Gender</ion-label>
  <ion-select placeholder="Select One" formControlName="Gender">
    <ion-select-option value="3">Female</ion-select-option>
    <ion-select-option value="2">Male</ion-select-option>
    <ion-select-option value="1">Other</ion-select-option>
    <ion-select-option value="0">Prefer Not to Say</ion-select-option>
 </ion-select>
</ion-item>

 ... more stuff
<ion-button expand="full" type="submit">Submit</ion-button>

</form>

我的代码是:

  ngOnInit() {

    this.userDetailsForm = this.formBuilder.group({
    ... some stuff
     Gender: [],
    });
    this.userService.getUserServer().subscribe (user => {
      // console.log('Patching the form');
      this.userDetailsForm.patchValue(user);
      ... other irrelevant code
    },
      error => this.helper.showAlert('We cant connect to the server at the moment msg is:' + error)
    );

  }

该字段总是显示为空(如图所示的占位符),我也尝试删除占位符并使用:

      <ion-select value ="3" formControlName="Gender">

无论我尝试什么,它都不会显示默认值或我设置的... 对不起,如果这很明显,但我错过了什么? 非常感谢。

编辑 我尝试删除其中的 formControlName="Gender" 部分,现在它可以工作了。当然,除了它不会成为反应形式的一部分......我觉得这闻起来有点错误 - 我将继续挖掘,同时欢迎任何进一步的想法。

您可以尝试使用占位符添加已选择的空选项:

<ion-select formControlName="Gender">
            <ion-select-option value="" selected="selected" hidden="hidden">Choose here</ion-select-option>
            <ion-select-option value="3">Female</ion-select-option>
            <ion-select-option value="2">Male</ion-select-option>
            <ion-select-option value="1">Other</ion-select-option>
            <ion-select-option value="0">Prefer Not to Say</ion-select-option>
</ion-select>

我已将此作为答案发布,以防其他人陷入困境。 我不确定它是否是由于我拥有的 ionic 4 的早期发布问题,但我通过 re-ordering ion-select 行修复了它。

 <ion-select placeholder="Select One" value = {{userDetailsForm.value.Gender}} formControlName="Gender" >
    <ion-select-option value="3">Female</ion-select-option>
    <ion-select-option value="2">Male</ion-select-option>
    <ion-select-option value="1">Other</ion-select-option>
    <ion-select-option value="0">Prefer Not to Say</ion-select-option>
 </ion-select>

将 'value = xxx' 放在 'formControlName = yyyy' 之前修复它。 这是一个奇怪的...