Set selected item in select list - Angular2

2019-03-03 15:56发布

I have the following data structure in my firebase table:

enter image description here

Inside my Angular2 application I retrieve the entries and and display them in a select list as shown here:

<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>

As you can see my first item in the list is a please select, this is selected by default before they have saved their profile. The issue I have is when they have saved their profile and reloaded the edit profile page the selected value is of course 'please select' when it should be either male or female.

After some searching I added the following attribute [selected] my code now looks like this:

<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>

However when running the project, it selects male as default even if I delete the value from Firebase it'll always remain as male selected.

Regarding what I'm doing inside my ts file, I simply call Firebase build the select list, then call get User Profile, I then pass the profile values into my form setup (reactive).

So my question is, how can I have Please Select as selected if the user has not specified their gender, or if they have specified their gender then set the relevant item to selected.

NOTE: I use the uniqueId generated by firebase as the value that is saved when the user saves their profile.

This is the part where I configure my form:

// 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)
 });

After the editProfileForm has been configured, it clear shows the value of gender:

enter image description here

2条回答
够拽才男人
2楼-- · 2019-03-03 16:11

It's because editProfileForm.controls.gender is always true (it is the form control instance itself), you have to check if the value of editProfileForm.controls.gender.value is the same as status.id

查看更多
贪生不怕死
3楼-- · 2019-03-03 16:18

The value in the userProfile.gender should be related to the option value, so it became selected.

<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> 
查看更多
登录 后发表回答