get the default value of select one menu

Viewed 96

I have two classes where the mapping is:

User *--------------------1 Sexe

I have the list of users on list-users.component.html. After selecting one user for modification, I'll be redirected to modify-user.component.html

Bellow are the required files: * the list-users.component.html is:

<table class="table">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Sexe</th>
        </tr>
    </thead>
    <tbody *ngIf="!loader">
        <tr *ngFor="let user of userbs | async" style="width: 1500px;">
            <td>{{user.id}}</td>
            <td>{{user.name}}</td>
            <td>{{user.sexe.libelle}}</td>
        </tr>
    </tbody>
</table>

where userbs is obtained by using the service userService.getUsersList() with the type Observable<User[]>.

the modify-user.component.html is:

<form [formGroup]="editForm" (ngSubmit)="onSubmit()">

    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" formControlName="name" placeholder="Name" name="name" class="form-control" id="name">
    </div>

    <div class="form-group">
        <label for="name">Sexe</label>

        <select (change)="onChangeSexeName($event)" class="form-control select2" style="width: 100%;">
            <option *ngFor="let sexe of sexes" [ngValue]="sexe" [selected]="selected">{{sexe.name}}</option>
        </select>
        ==> Original Sexe: {{selectedSexeUserCompare.name}}
    </div>

    <button class="btn btn-success">Update</button>
</form>

and modify-user.component.ts is:

export class ModifyUserComponent implements OnInit {
    editForm: FormGroup;
    submitted = false;
    private selectedSexe;
    users: Observable<User[]>;
    libelleSexe: string;
    usrId: String;
    selectedSexeUserCompare = { num: localStorage.getItem("selectedSexeId"), name: localStorage.getItem("selectedSexeName") }
    sexeName: String;

    sexes: Array<Object> = [
        { num: 1, name: "Female" },
        { num: 2, name: "Male" }
    ];

    compareFn(a, b) {
        console.log(a, b, a && b && a.num == b.num);
        return a && b && a.num == b.num;
    }

    constructor(private formBuilder: FormBuilder, private router: Router, private userService: UserService) { }

    ngOnInit() {
        this.sexeName = localStorage.getItem("sexeLibelle");

        let userId = localStorage.getItem("editUserId");
        this.usrId = localStorage.getItem("editUserId");
        if (!userId) {
            alert("Invalid action.")
            this.router.navigate(['users-list']);
            return;
        }

        this.userService.getUserEntityId(+userId).map(se => se.sexe.libelle).subscribe((response) => {
            this.libelleSexe = response;
            localStorage.setItem("sexeLibelle", this.libelleSexe);
        });

        this.editForm = this.formBuilder.group({
            id: [],
            name: ['', Validators.required],
            username: ['', Validators.required],
            email: ['', Validators.required],
            password: ['', Validators.required],
            age: ['', Validators.required],
            active: ['false']
        });

        this.userService.getUserId(+userId).subscribe(data => {
            this.userService.getUserEntityId(+userId).map(se => se.sexe.libelle).subscribe((response) => {
                this.libelleSexe = response;
                let sexe = this.userService.getSexeByLibelle(this.libelleSexe);
                localStorage.setItem("sexeLibelle", this.libelleSexe);
                this.editForm.patchValue(data);
            });
        });
    }

    onChangeSexeName($event) {
        this.selectedSexe = $event.target.options[$event.target.options.selectedIndex].text;
    }

    onSubmit() {
        this.userService.updateUsera(this.editForm.value, this.selectedSexe).subscribe(data => {
            this.router.navigate(['users-list']);
        },
            error => {
                alert(error);
            });
    }
}

On modify-user page, I get usually the first sexe libelle of the list of sexes (Female, Male) and NOT the correct sexe libelle, exactly like this screenshot displayed.

Could you please help me solving that issue ?. Thanks a lot.

1 Answers

I'm not sure as to why you are not adding sex to your editForm. Add sex to your editForm and initialize it with the value stored in your localStorage.

this.editForm = this.formBuilder.group({
    sex: [selectedSexeUserCompare.num, Validators.required]
    // Add form controls here
});

Another issue I noticed in your HTML is that you are setting the ngValue in your options to the entire sexe object. You should rather set it to a unique value such as the num property in your sexe object.

modify-user.component.html

<select formControlName="sex" (change)="onChangeSexeName($event)" class="form-control select2" style="width: 100%;">
    <option *ngFor="let sexe of sexes" [ngValue]="sexe.num">
        {{sexe.name}}
    </option>
</select>

Edit: Here is a working example on StackBlitz

Related