如何在angular8的下拉菜单中设置初始值 [英] How to set initial value in dropdown in angular8

查看:48
本文介绍了如何在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>

该值不是使用上面的代码设置的.它在ng反射模型中显示,但不在UI中显示

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

推荐答案

您可以像下面这样使用ngModel绑定来完全实现此目的:

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

component.ts

component.ts

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

component.html

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];

收件人:

selected = this.objects[0];

Stackblitz示例: https://stackblitz.com/edit/angular-esulus

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

这篇关于如何在angular8的下拉菜单中设置初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆