0

I have a select box tied to an ngModel:

tempHours = [
    {},
    {},
    {},
    ...
]

<select name="repeat" [(ngModel)]="tempHours[index].repeat">
    <option value="Every" selected>Every Day</option>
    <option value="Every Other">Every Other Day</option>
</select>

When this code is reached for the first time, tempHours[index] is an empty object. So the ngModel is inserting an option tag with undefined value and blank text and not respecting the selected attribute.

In reading up on the angular bug trackers, they defend this as a feature not a bug, but this is clearly not desired behavior. I could go through and predefine all the tempHours objects to have repeat be "Every", but there has got to be a more elegant way for ngModel to fall back to the html attribute if it is undefined.

Any suggestions? Or am I just going to have to predefine the tempHours objects for the repeat?

mycroft16
  • 785
  • 10
  • 28

1 Answers1

0

You could do something like this:

<select name="repeat" 
    [ngModel]="tempHours[index]?.repeat || 'Every'" 
    (ngModelChange)="onRepetitionChange(index, $event)">
  <option value="Every">Every Day</option>
  <option value="Every Other">Every Other Day</option>
</select>

And on script side:

onRepetitionChange(index, newValue) {
  if (!this.tempHours[index]) {
    this.tempHours[index] = {};
  }
  this.tempHours[index].repeat = newValue;
}

The idea is to split [(ngModel)] into two parts:

  • [ngModel] to use ?. (existential operator) and have a default value if the key doesn't exist,
  • (ngModelChange) to handle what happens when the selected option changes.

StackBlitz Demo

Jeto
  • 14,596
  • 2
  • 32
  • 46
  • As a note, this will select the correct value in the UI but will not initialize the `repeat` property with the value "Every". – Daniel W Strimpel Mar 12 '18 at 20:41
  • I just brought it up because the OP stated > I could go through and predefine all the tempHours objects to have repeat be "Every", but there has got to be a more elegant way for ngModel to fall back to the html attribute if it is undefined. – Daniel W Strimpel Mar 12 '18 at 21:20
  • @DanielWStrimpel Yeah sorry I deleted my comment as I reread the OP. Good point. – Jeto Mar 12 '18 at 21:21