I have the following data structure in my firebase table:
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:
It's because
editProfileForm.controls.gender
is alwaystrue
(it is the form control instance itself), you have to check if the value ofeditProfileForm.controls.gender.value
is the same asstatus.id
The value in the
userProfile.gender
should be related to the option value, so it became selected.