0

How do I automatically convert data from string to number?

My data is not clear what it is and I want it to be automatically converted according to the type it has

html:

<form [formGroup]="formUser">
  <label>name: </label>
  <input formControlName="name" >
  <br>
  <label>name: </label>
  <input formControlName="userId" >
</form>
<button (click)="send()">send</button>

ts:

    export class AppComponent  {
      constructor(private fb:FormBuilder){
    
      }
      formUser=this.fb.group({
        name:null,
        userId:null,
      })
       send(){
    const user:IUser=this.formUser.value
    console.log(user);
  }
}
interface IUser{
  name:string,
  userId:number
}

console:

{name: "alis", userId: "12"} 

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

I do not want to use the following method:

user.userId=Number(user.userId)
5
  • parseInt(number, 10) ? Commented Jun 24, 2021 at 6:33
  • Do you mean on change? Or when the Component is built? Or formatting the Value/Input? Commented Jun 24, 2021 at 6:37
  • Angular cli : 11.1.4, node 14.17.0 , Angular 11.1.2 , typescript:4.1.5 Commented Jun 24, 2021 at 6:38
  • I just gave an example otherwise my data can be anything and I do not want to change all the data manually Commented Jun 24, 2021 at 6:41
  • 3
    You can specify a type attribute in your input which is being respected... Commented Jun 24, 2021 at 6:42

2 Answers 2

1

If the userId is always number you can use

<input formControlName="userId" type="number" />

So by default it will be of type number only.

Sign up to request clarification or add additional context in comments.

Comments

0

A simple way to convert string values to number is by using the unary plus operator +:

user.userId = +user.userId;

More reference here

1 Comment

It doesn't answer the question, he wants it to be converted automatically, not manually using "+" or "Number(..)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.