Reputation: 414
I was creating a form for editing a user's data, but I came to an impasse when I needed to use two "selects" in the form.
The curiosity here is that a select works correctly and the other does not.
My code in component.ts:
teams = [
{id: 0, name: Team[Team.Mobile]},
{id: 1, name: Team[Team.Frontend]},
{id: 2, name: Team[Team.Backend]}
]
genders = [
{id: 0, name: Gender[Gender.Male]},
{id: 1, name: Gender[Gender.Female]},
{id: 2, name: Gender[Gender.Other]},
]
employeeForm = this.formBuilder.group({
name: '',
gender: [2],
birthDate: '',
email: '',
startDate: '',
cpf: '',
team:[2]
});
ngOnInit(): void {
this.peopleService.getPeopleById(this.list[0].employeeId)
.subscribe(
people => {
this.employee = people;
this.employeeForm.patchValue({
name: people.name,
gender: [people.gender],
birthDate: new Date(people.birthDate),
email: people.email,
startDate: new Date(people.startDate),
cpf: people.cpf,
team: [people.team]
});
},
error => console.log(error)
);
}
get gender() {
return this.employeeForm.get('gender').value;
}
get team() {
return this.employeeForm.get('team').value;
}
My HTML template:
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
...
<div class="form-group">
<label for="gender">Gender</label>
<select class="form-control" id="gender" formControlName="gender">
<ng-container *ngFor="let genderEl of genders">
<option [ngValue]="genderEl.id" [selected] = "gender == genderEl.id">{{genderEl.name}}</option>
</ng-container>
</select>
</div>
<div class="form-group">
<label for="team">Team</label>
<select class="form-control" id="team" formControlName="team">
<ng-container *ngFor="let teamEl of teams">
<option [ngValue]="teamEl.id" [selected] = "team == teamEl.id">{{teamEl.name}}</option>
</ng-container>
</select>
</div>
...
</form>
I've already tried to make a conditional container to do the same thing, it even works for the gender block, but when I do the same thing for the "team" select, it's the same way as the print.
Print of how it's appearing on the screen:
Upvotes: 0
Views: 98
Reputation: 51195
The reason why gender
and team
were not working is due to this logic:
[selected]="team == teamEl.id"
When team
is an array (for example: [2]), the comparison logic will be:
[selected]="[2] == 2"
In which both values to be compared are different values and types.
This logic works fine as the requirement confirmed that team
and gender
are not an array.
Hence, you are not required to cast people.gender
and people.team
to the array, which would break the existing logic.
this.employeeForm.patchValue({
...,
gender: people.gender,
team: people.team
});
Upvotes: 3