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

在我的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>但是,在运行项目时,它选择male作为默认值,即使我从Firebase中删除该值,它也将始终保持为男性选择。
关于我在ts文件中所做的事情,我只需调用Firebase构建选择列表,然后调用get用户配置文件,然后将配置文件值传递到我的表单设置中(反应性)。
所以我的问题是,如果用户没有指定他们的性别,或者如果他们指定了他们的性别,那么我如何才能选择Please Select,然后将相关的项目设置为selected。
注意:我使用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之后,它清楚地显示了性别的价值:

发布于 2017-03-05 22:07:27
因为editProfileForm.controls.gender总是true (它是表单控件实例本身),所以必须检查editProfileForm.controls.gender.value的值是否与status.id相同
发布于 2017-03-05 22:15:19
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> https://stackoverflow.com/questions/42614208
复制相似问题