1

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'}
  ];

1
  • What is the problem of converting it to 'undefined'? Commented Aug 5, 2020 at 4:04

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

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.