设置 FormControl 的值会破坏其类型

Setting the value of a FormControl breaks its type

我有这个 FormGroup 和这个 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 是一个数字,FormControl userRole 映射到后端的 C# 枚举。

当我像这样提交此表单时,它起作用了,我在操作方法中获得了正确的数据,其中包含正确的枚举值。

但是当我改变 userRole FormControl 的值时,像这样:

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

这是由下拉菜单上的更改事件触发的 select

问题是当我提交表单时,值变成了字符串。我可以通过查看 Chrome 的网络选项卡来确认这一点(当它工作时,userRole: 10,当它在 UI 中的值更改后失败时,userRole: "10"

这是提交给控制器的方式:

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

User class:

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

我该如何解决?

我假定 userRole 已分配给 <select> 元素,对吗?

如果是,则对 <option> 元素使用 [ngValue] 而不是 [value]

[value] 只能保存字符串值。

在提交表单之前将 userRole 从字符串转换为数字数据类型。

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