0

I have this FormGroup with this FormControl

this.userForm = new FormGroup({
    id: new FormControl(this.user.id),
    firstName: new FormControl(this.user.firstName),
    lastName: new FormControl(this.user.lastName),
    email: new FormControl(this.user.email),
    password: new FormControl(""),
    userRole: new FormControl(this.user.userRole)
});

this.user.userRole is a number and the FormControl userRole maps to a C# enum in the back end.

When I submit this form like this, it works, I get the proper data in the action method with the correct value for the enum.

But when I change the value of the userRole FormControl, like this:

changeRole(e) {
    this.userForm.get('userRole').setValue(parseInt(e.target.value), {
        onlySelf: true
    });
}

This is triggered by a change event on a dropdown select.

The problem is when I then submit the form, the value is turned to a string. I can confirm this by looking in Chrome's network tab (when it works, userRole: 10, when it fails after the value in the UI was changed, userRole: "10"

This is how it's submitted to the controller:

onSubmit() {
    this.userService.save(this.userForm.value as User).subscribe(r => {
      this._bsModalRef.hide();
    });
}

//the service's method....
save(user: User): Observable<any> {
    let url = "/user/save";
    return this.http.post(url, user);
}

And the User class:

export class User {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  userRoleDisplay: string;
  userRole: number;
  lastLogin: string;
  password: string
}

How can I solve that?

Francis Ducharme
  • 4,848
  • 6
  • 43
  • 81

2 Answers2

2

I assume userRole is assigned to a <select> element, correct?

If yes, then use [ngValue] for the <option> elements instead of [value].

[value] can only hold string values.

Eyad Arafat
  • 601
  • 8
  • 19
1

Convert the userRole from string to number data type before submitting the form.

onSubmit() {
    const user = this.userForm.value;
    
    // Convert userRole from string to number
    user.userRole = +user.userRole;
    
    this.userService.save(user as User).subscribe(r => {
      this._bsModalRef.hide();
    });
}
Lahiru Tennakoon
  • 621
  • 1
  • 6
  • 8