User123
User123

Reputation: 833

How to set initial value in dropdown in angular8

I have two items in dropdown. I need to set initial value as first value from array below is my code

objects = ['production', 'development'];
this.object = this.objects[0];

<div class="item">
  <select formControlName="db" class="form-control" (change)="changeDb($event)" [ngModel]="object">
    <option *ngFor="let object of objects" [ngValue]="object">{{object}}</option>
</select>
</div>

The value is not setting using above code.It is showing in ng reflect model but not in UI

Upvotes: 0

Views: 2251

Answers (2)

Adamski
Adamski

Reputation: 889

You can cleanly achieve this by using the ngModel binding like so:

component.ts

export class AppComponent  {
  objects = ['production', 'development'];
  // The selected node of the objects array
  selected = this.objects[1];
}

component.html

<div class="item">
  <select class="form-control" (change)="changeDb($event)" [ngModel]="selected">
    <option *ngFor="let object of objects">{{object}}</option>
  </select>
</div>

The above code as it is would preselect the 'development' node of the objects array.

So in your case to preselect the first option, you would change:

selected = this.objects[1];

to:

selected = this.objects[0];

Example Stackblitz: https://stackblitz.com/edit/angular-esulus

Upvotes: 1

paulhenry
paulhenry

Reputation: 137

You can add an "if" statement if your default object is equal to the object in your array then add selected attribute in your element. Also change your variable name to maybe "defaultObject" to not conflict in your "for of" statement.

objects = ['production', 'development'];
this.defaultObject = this.objects[0];

<div class="item">
  <select formControlName="db" class="form-control" (change)="changeDb($event)" [ngModel]="object">
    <option *ngFor="let object of objects" [ngValue]="object" [selected]="defaultObject == object">{{object}}. 
    </option>
  </select>
</div>

Upvotes: 0

Related Questions