Assigning a new value to a FormControl can alter its data type

I am facing an issue with my FormGroup and 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)
});

The this.user.userRole is a numerical value that corresponds to a C# enum.

When I submit the form as it is, everything works correctly, and the backend receives the appropriate data with the correct enum value.

However, if I change the value of the userRole FormControl using:

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

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

The problem arises when I submit the form after changing the userRole value. The numeric value gets converted to a string. This discrepancy can be seen in Chrome's network tab (initially reads userRole: 10, but changes to userRole: "10").

Here is how the submission is done 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);
}

Additionally, here is the structure of the User class:

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

Any suggestions on how to address this?

Answer №1

Is it safe to assume that the userRole is linked to a <select> element?

If this is indeed the case, consider utilizing [ngValue] for the <option> elements rather than [value].

Note that [value] is only capable of storing string values.

Answer №2

Make sure to convert the userRole field from a string to a number data type before you submit the form.

onSubmit() {
    const user = this.userForm.value;
    
    // Ensure userRole is of number data type
    user.userRole = +user.userRole;
    
    this.userService.save(user as User).subscribe(r => {
      this._bsModalRef.hide();
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Installing and importing Angular Google Maps in an Angular 2 application using TypeScript: A step-by-step guide

Can you provide step-by-step instructions on integrating angular-google-maps into an Angular 2 application and importing it for use in a TypeScript component? ...

What is the proper method for utilizing TypeScript declarations (*.d.ts) and interfaces?

When working with interfaces in TypeScript, there are two main approaches to consider. The first involves defining them in regular .ts files and importing them as needed. The second option is to define the interfaces in .d.ts files and let the compiler dis ...

Different Approaches for Handling User Interactions in Angular Instead of Using the Deferred (Anti-?)Pattern

In the process of developing a game using Angular, I have implemented the following mechanics: An Angular service checks the game state and prompts a necessary user interaction. A mediator service creates this prompt and sends it to the relevant Angular c ...

Are getter and setter pairs permitted to override properties in the base class of JavaScript/TypeScript?

Recently, there has been an update in TypeScript that triggers a compilation error when attempting to override a property in the base class with a getter/setter pair. This issue arises from property access augmentation: class BaseClass { prop : ...

The inner panel height does not extend to 100% when there is overflow

When pressing the submit button on a panel containing components, an overlay appears but does not cover the entire parent panel if scrolled to the bottom. Additionally, I want the spinner to always be centered, whether scrolling or not. I've tried usi ...

What steps should I take to create a React component in Typescript that mimics the functionality of a traditional "if" statement?

I created a basic <If /> function component with React: import React, { ReactElement } from "react"; interface Props { condition: boolean; comment?: any; } export function If(props: React.PropsWithChildren<Props>): ReactElement | nul ...

Prevent redirection when submitting and show an error message instead

I implemented a login system where, upon entering the correct username and password, a token is stored in local storage. If there's an error with the credentials, an "Login Unsuccessful" message is displayed. Everything was functioning correctly until ...

Angular 6's ngFor directive allows for dynamic rendering of arrays

I'm facing an issue with two sets of code - one works, and the other doesn't. I need to understand why. Not Working: <p *ngFor="let recp of recipes"> <div class="row"> <div class="col-xs-12"> <a href="#" class=" ...

Develop a simulated version that does not include all the functionalities of the primary service

Let's imagine a scenario where there is an OriginalService class with various methods class OriginalService { method1() { } method2() { } method3() { } .. } Now, suppose we need to create a mock of OriginalService that will only be used with ...

In Angular, the error message "Type 'NavController' does not contain a property 'push'" indicates that the NavController does not have a push property

While working on my Ionic app, I encountered an issue with navigating to another page and passing a variable using this.navCtrl.push(). Unfortunately, it isn't working as expected. What could be causing this problem? Any suggestions would be greatly a ...

Screening properties before condensing

I am currently facing an issue where I need to map an Object to HttpParams while excluding any parameter that is empty, null, or undefined. export function mapToHttpParams(obj: object): HttpParams { return Object.getOwnPropertyNames(obj) .reduce((p, ...

Angular Form Template Unidirectional Data Binding Example

I'm facing a challenge with one-way binding to a default value in my HTML form. Within my component, I have a Connection string that is initially set from local storage: export class AuthAdminComponent implements OnInit { public authenticated = f ...

Developing web parts with Angular 2 for SharePoint 2013

Seeking advice on how to create a web part for SharePoint 2013 farm solution utilizing WCF custom Rest Services to retrieve data from the content database using server object model. I also aim to incorporate Angular 2 to consume these services within the ...

The error message "TypeError: (0 , N.createContext) is not a function" indicates that

I'm currently in the process of developing a cutting-edge application using Next.js 14, TypeScript, and Telegram Open Network. However, I've hit a roadblock while attempting to incorporate the TONConnectUIProvider at the root of my app. Upon run ...

Building a user interface with React JS to iterate over an array using the map function, passing each item as a parameter

I have been instructed to create an interface for my code related to .map, but I am unsure about how to proceed. I have been searching for examples without any luck so far. I have isolated the specific code with ###. Any assistance in this matter would be ...

Is there a way to integrate the AuthState TypeScript Interface into the react-oidc-context Node package for testing in Next.js?

We are currently working on a Next.js application that utilizes the react-oidc-context Node module for authentication with ADFS. During our testing phase using Vitest, we encountered the following error: TypeError: Cannot read properties of undefined (rea ...

Cross-origin error triggered by using an external API within a ReactJS application

I'm facing a common CORS issue in my application while trying to call an API. The API I am attempting to access can be found here: https://github.com/nickypangers/passport-visa-api Below is the code snippet used for making the API call: const getVi ...

"Once the login is successful, what is the best way to conceal

Upon successful login, I need to automatically close my popup. The code I have written for this purpose is displayed below, but unfortunately it is not functioning as expected. Can someone provide guidance and assistance? My HTML <div class=" ...

Guide on automatically inserting a colon (:) after every pair of characters in Angular

I am looking to automatically insert a colon (:) after every 2 characters in my input field: HTML <input nz-input type="text" appLimitInput="textAndNumbers" name="mac" formControlName="mac" (keydown.space)=&qu ...

Tips for minimizing delay after user input with Material UI

Background I'm currently working on a website project that includes a carousel of MUI cards using a unique stack as the underlying component. However, I've encountered an issue where there is a noticeable 4-second delay whenever I try to scroll ...