How to set initial value in dropdown in angular8

别等时光非礼了梦想. 提交于 2021-02-17 05:39:05

问题


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


回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/64064480/how-to-set-initial-value-in-dropdown-in-angular8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!