select option with default value undefined with required attribute does not work but value empty

asdf_enel_hak picture asdf_enel_hak · Feb 7, 2019 · Viewed 9.5k times · Source

I have a dropdown of countries

<select  #countryInput  name="country" [(ngModel)]="room.countryId"   required>
  <option   [selected] [value]="undefined">Select Country</option>
  <option *ngFor="let c of countries" [value]="c.id">{{c.name}}</option>
</select>

In order to "Select Country" option, it is required to set [value]="undefined" otherwise it would not be shown as default selection instead empty selection.

Even though field marked is as required, on form submit required wont be show as it does for

<option value="">Select Country</option> 

which is default behaviour in html 5:

enter image description here

As a work around handle validation on form submit, but this time first required fields will be validated but lastly country field.

if (this.room.country == undefined) {
   alert('select country ');
   return false;
}

What could be solution to field with [value]="undefined" and show "Please select an item first" alert?

See the forked fiddle from Daniel's

Answer

Vikas Dubey picture Vikas Dubey · Jun 5, 2019

i also had the same issue using following solved the problem for me

 <select class="o-field__input" [disabled]="isAnswerPresent" [(ngModel)]="inputValue" (change)="onAnswerChange()" required>
                <option [ngValue]="undefined">placeholder</option>

                <option [ngValue]="option" *ngFor="let option of optionSet;">option values</option>                     

            </select>