【问题标题】:Set selected item in select list - Angular2在选择列表中设置所选项目 - Angular2
【发布时间】:2017-07-25 15:34:29
【问题描述】:

我的 firebase 表中有以下数据结构:

在我的Angular2 应用程序中,我检索条目并将它们显示在select list 中,如下所示:

<select class="form-control" id="lookingFor" formControlName="gender" >
   <option value="" selected>Please Select</option>
   <option *ngFor="let status of genderValue" [value]="status.id">{{ status.description}}</option>
</select>

如您所见,我在列表中的第一项是“请选择”,默认情况下,这是在他们保存个人资料之前选择的。我遇到的问题是当他们保存了他们的个人资料并重新加载了编辑个人资料页面时,当它应该是男性或女性时,选择的值当然是“请选择”。

经过一番搜索,我添加了以下属性 [selected] 我的代码现在看起来像这样:

<select class="form-control" id="lookingFor" formControlName="gender" >
       <option value="" selected>Please Select</option>
       <option *ngFor="let status of genderValue" [value]="status.id" [selected]="editProfileForm.controls.gender">{{ status.description}}</option>
    </select>

但是,在运行项目时,即使我从 Firebase 中删除该值,它也会选择 male 作为默认值,它仍将始终保持为男性选择。

关于我在 ts 文件中所做的事情,我只需调用 Firebase 构建选择列表,然后调用 get User Profile,然后将配置文件值传递到我的表单设置中(反应式)。

所以我的问题是,如果用户没有指定他们的性别,或者如果他们指定了他们的性别然后将相关项目设置为选中,我如何选择 Please Select

注意:我使用 firebase 生成的 uniqueId 作为用户保存个人资料时保存的值。

这是我配置表单的部分:

// userProfile is returned from Firebase
// gender will either have a value or it'll be null.
this.editProfileForm = new FormGroup({
    seeking: new FormControl('', Validators.required),
    gender: new FormControl(this.userProfile.gender, Validators.required)
 });

editProfileForm配置完成后,明确显示gender的值:

【问题讨论】:

  • 当您从 firebase 中删除值时,请确保您使用新值更新了模型。
  • @RomanC 我已经这样做了,我还一起关闭了应用程序并重新启动它,但问题中上面概述的问题仍然存在
  • 您应该绑定存储所选值的属性
  • 我确实绑定了属性,它绑定到从 firebase 返回的用户配置文件。
  • 我需要请您发布代码吗?

标签: angular typescript angular2-forms


【解决方案1】:

因为editProfileForm.controls.gender总是true(就是表单控件实例本身),所以要检查editProfileForm.controls.gender.value的值是否和status.id一样

【讨论】:

  • 我可以在html 上这样做吗?
  • 我在html editProfileForm.controls.gender == status.id 中完成了以下操作,但是在选择male 后保存配置文件时重新加载页面并且所选项目为Please Select
  • 您确定this.userProfile.gendereditProfileFOrm.controls.gender 在创建表单时包含正确的值吗?
  • 我已将this.userProfile.gender 登录到控制台并看到了女性密钥。然后我检查了选择列表,发现女性的值与选择的选项相同。
  • 所以在这条线gender: new FormControl(this.userProfile.gender, Validators.required)得到处理你this.userProfile.gender的值是“女性”
【解决方案2】:

userProfile.gender 中的值应该与选项值相关,因此它被选中。

<select class="form-control" id="lookingFor" formControlName="gender" [(ngModel)]="userProfile.gender">
       <option value="" selected>Please Select</option>
       <option *ngFor="let status of genderValue" [ngValue]="status.id">{{ status.description}}</option>
    </select> 

【讨论】:

  • 您不能将ngModel 与模型驱动表单一起使用。
猜你喜欢
  • 1970-01-01
  • 2016-07-09
  • 1970-01-01
  • 2017-07-02
  • 2012-08-20
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
相关资源
最近更新 更多