Reputation: 281
I have been struggling to validate a Reactive form with default "select" option to my select input box when there's no value selected. If a value is present in the form then I need to select the respective value.
I am using reactive form and below is my code implementation:
<select class="form-control" formControlName="environment" >
<option disabled [value]="null">-- Select --</option>
<option *ngFor="let ami of envs" [value]="ami.amiid">
{{ami.name}}
</option>
</select>
this.onlineTestForm = this._fb.group({
.
.
environment: ['', Validators.required],
.
.
});
//value is present in the model
(<FormControl>this.onlineTestForm.controls['environment'])
.setValue(this.model.environment, { onlySelf: true });
//value is not present in model
(<FormControl>this.onlineTestForm.controls['environment'])
.setValue('null', { onlySelf: true });
Is there a better way to achieve the above?
Upvotes: 0
Views: 2251
Reputation: 73357
Your problem is here:
(<FormControl>this.onlineTestForm.controls['environment'])
.setValue('null', { onlySelf: true });
you are setting string value 'null'
instead of null
. The string 'null'
is of course a valid value.
Also you are setting a complete object as the value of the form control if it exists, even though environment
expects just the id, at least what you have specified in the template:
[value]="ami.amiid"
I see two options here to "improve" your code. These depend on if this.model
gets the values asynchronously or not. If you know the value of this.model
on initialization, you can simply do this:
environment: [this.model.environment || null,
Validators.required]
Here we must remember to initialize model
as an empty object, so that an undefined
error will not be thrown in case there is no value in model
.
If model
value is set asynchronously, use setValue
to set the value once you get it:
this.onlineTestForm.controls.environment.setValue(...)
Upvotes: 3