Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Reactive forms Select default object

I'm using reactive forms and I have a select box that comes from an array of objects. I tried to set the default value but it just doesn't set.

My form:

<form [formGroup]="markerForm" (ngSubmit)="onSubmit(markerForm)" novalidate>
      <div class="form-group">
        <label for="markerType">{{ 'MARKER.LABEL_TYPE' | translate }}</label>
        <select  class="form-control" formControlName="markerType"   >
           <option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>
        </select>
      </div>
</form>

Set default value:

const test= [{id:1, desc: 'Restaurants'}, {id:2, desc : 'Fire stations'}];
this.markerTypes= test;
console.log(this.markerTypes[1].desc);
this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});
like image 428
John Avatar asked Sep 23 '26 11:09

John


2 Answers

The problem happened because you are using markerType.id as a value but sending the whole object this.markerTypes[1] as default. You should pass this.markerTypes[1].id in this case.

If you want to use objects as values you should use ngValue directive on option tag:

<option id="markerType" [ngValue]="markerType" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

This is because unlike the value binding, ngValue supports binding to objects

See the working example here

like image 186
Sergey Mell Avatar answered Sep 26 '26 02:09

Sergey Mell


You're setting your default value as an Object:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});

And you're saying that your value is an id:

 <option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

You have multiple choices here, it depends how you want your form value to be.

Using Id:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1].id, {onlySelf: true});

<option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

Using Desc:

this.markerForm.controls['markerType'].setValue( this.markerTypes[1].desc, {onlySelf: true});

<option id="markerType" [value]="markerType.desc" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

Using Object:

In this case you have to use [ngValue], [value] is used only for type string variables.

this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});

<option id="markerType" [value]="markerType" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>

Working Example

like image 45
VascoCC Avatar answered Sep 26 '26 02:09

VascoCC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!