Angular2 reactive forms choose how to set invalid?
I am using reactive forms in my application. In a specific form, I want to display the required (Validators.required), for example:
<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 am using value="undefined"
or value=""
that the format control is still set as valid as it got the value. Don't show attribute value
in value="Choose ..."
.
I use select with reactive forms of false way, or how I can make the parameter "Choose ..." is not a valid ??
source to share
What I am doing is add an empty parameter and when this is selected, since there is no value, it is invalid.
<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>
source to share
Initializing the select control null
will do the trick. Try below,
model_property = null
....
this.fb.group({
....
'control_key' : [this.model_property, Validators.required]
...
})
Check out Plunker !! , view the file app/reactive/hero-form-reactive.component.ts
.
I have updated Plunker to include below and it seems to work,
<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>
Hope this helps!
source to share