0

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

User123
  • 793
  • 4
  • 10
  • 28
  • 1
    Does this answer your question? [Select default option value from typescript angular 6](https://stackoverflow.com/questions/51009331/select-default-option-value-from-typescript-angular-6) – Balaj Khan Sep 25 '20 at 12:53
  • No i tried that but no luck – User123 Sep 25 '20 at 13:05

2 Answers2

1

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

Adamski
  • 839
  • 2
  • 10
  • 28
0

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>
paulhenry
  • 111
  • 5
  • I tried your answer but still value is not being set in dropdown. – User123 Sep 25 '20 at 13:22
  • Did you try changing the other initial variable to this.defulatObject? and added [selected]="defaultObject == object"? I tried your code just edited these parts and it works. – paulhenry Sep 25 '20 at 13:27
  • Yes i had changed – User123 Sep 25 '20 at 13:35
  • 1
    Can you try this Code: I have this simplified approach for you to test. In your HTML file:
    In your .ts file import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { public objects = ['production', 'development']; public defaultObject = this.objects[2]; }
    – paulhenry Sep 25 '20 at 15:10