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

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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>

4 Comments

I tried your answer but still value is not being set in dropdown.
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.
Yes i had changed
Can you try this Code: I have this simplified approach for you to test. In your HTML file: <div class="item"> <select> <option *ngFor="let object of objects" [ngValue]="object" [selected]="defaultObject == object">{{object}}. </option> </select> </div> 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]; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.