0

I have a select element with options in component.html file as:

<select name="balanceRounding" id="generalBalanceRounding" class="form-control" formControlName="balanceRounding">
    <option *ngFor="let balRounding of balRoundings 
        [value]="balanceRounding.value">{{balRounding.text}}
    </option>
</select>

and in component.ts file, I have:

balRoundings = [
        { text: 'No Rounding', value: null },
        { text: '0.01', value: 0.01 },
        { text: '0.02', value: 0.02 },
        { text: '0.05', value: 0.05 },
        { text: '0.10', value: 0.10 },
        { text: '0.20', value: 0.20 },
        { text: '0.50', value: 0.50 },
        { text: '1.00', value: 1.00 }
];

Now, when I select any value from the dropdown, I am getting selected value as string in balanceRounding (formControlName).

i.e. If I select 0.05, then I have balanceRounding as '0.05'

If I select 'No Rounding', then I have balanceRounding as 'null'

I just don't understand why my values are getting converted to a string.

Could anyone suggest me how to have values of having type as it is?

Thanks in advance.

Ashish Kumar
  • 401
  • 4
  • 11

2 Answers2

2

I would suggest you use [ngValue] directive instead of [value] as to my expirience with it, it preserve data types such as numbers and even you can pass in objects.

Qellson
  • 532
  • 2
  • 7
1

The correct way of doing it is using ngValue.

It's ok to use value or ngValue. The only difference between two is that value is always a string, where in ngValue you can pass object.

 <select name="balanceRounding" id="generalBalanceRounding" class="form-control" formControlName="balanceRounding">
    <option *ngFor="let balRounding of balRoundings" 
        [ngValue]="balRounding.value">{{balRounding.text}}
    </option>
</select>

Here is the stackblitz to solve your problem,

https://stackblitz.com/edit/angular-reactive-forms-bpx2ts?file=app/app.component.html

In the console, you should be able to see the output of the respective form

Hope it helps!

Suhas Parameshwara
  • 1,344
  • 7
  • 15