3
votes

I use reactive forms within my app. In a certain form I want to display a required (Validators.required) select like this:

<select class="form-control"
        [id]="dformControl.key"
        [formControlName]="dformControl.key"
        [multiple]="dformControl.multiple">

  <option *ngIf="!dformControl.value"
          value="undefined">
    Choose ...
  </option>

   <option *ngFor="let opt of dformControl.options"
          [value]="opt.value"
          [selected]="dformControl.value == opt.value">
    {{opt.label}}
  </option>

</select>

The problem is whether I use value="undefined" or value="" the form control still is set to valid because it got a value. Do not present the value attribute results in value="Choose ...".

Am I using select with reactive forms in a false way or how would I be able to make the option "Choose ..." being not valid??

2

2 Answers

0
votes

What I do is add a blank option and when that is selected since there is no value it is not valid.

<select class="form-control"
        [id]="dformControl.key"
        [formControlName]="dformControl.key"
        [multiple]="dformControl.multiple">

  <option></option>
   <option *ngFor="let opt of dformControl.options"
          [value]="opt.value"
          [selected]="dformControl.value == opt.value">
    {{opt.label}}
  </option>
</select>
3
votes

Assigning initial value of select control to null will do the trick. Try below,

  model_property = null

  ....
  this.fb.group({ 
  .... 
  'control_key'  :    [this.model_property, Validators.required]
  ...
  })

Check this Plunker!!, Look into app/reactive/hero-form-reactive.component.ts file.

I updated the Plunker to include below and it seems to be working,

    <select id="power" class="form-control"
        formControlName="power" required >

        // see the value is set to empty,
        <option value="">Choose...</option>

        <option *ngFor="let p of powers" [value]="p">{{p}}</option>
    </select>

enter image description here

Hope this helps!!