chuckd
chuckd

Reputation: 14530

Why is typescript converting number to string?

I have a dropdown with these values below and when I first use the initial value it's undefined. But then after I change to '30 min' then back to 'Any' the property I'm using as the ngModel gets set from 30 to 'undefined'! It gets set to a string?

The actual property looks like this below - I didn't realize typescript would convert it like that?

length: number;

where my dropdown is here

<div class="form-group">
  <label for="length">Length</label>
  <select class="form-control w-100" id="length" name="length" [(ngModel)]="eventParams.length">
    <option *ngFor="let length of lengthList" [value]="length.value">
      {{length.display}}
    </option>
  </select>
</div>

  lengthList = [
    {value: undefined, display: 'Any'},
    {value: 30, display: '30 min'},
    {value: 45, display: '45 min'},
    {value: 60, display: '60 min'},
    {value: 90, display: '90 min'}
  ];

Upvotes: 1

Views: 250

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27303

As mentioned in the Angular documentation

Value attribute tracks simple string values bound to the option element. For objects, use the ngValue input binding.

Use ngValue attribute it will work as expected.

<div class="form-group">
      <label for="length">Length</label>
      <select class="form-control w-100" id="length" name="length" [(ngModel)]="eventParams.length">
        <option *ngFor="let length of lengthList" [ngValue]="length.value">
          {{length.display}}
        </option>
      </select>
    </div>

Upvotes: 3

Related Questions