简体   繁体   English

在angular2中动态初始化选择值

[英]Initializing Select value dynamically in angular2

I am setting value of select option in a loop . 我在循环中设置选择选项的值。 Have a look at the code 看一下代码

<div *ngFor="let sport of sport_data;" class="row">
  <select [(ngModel)]="sports.value" class="form-control">
      <option value="football">Sports</option>
      <option value="cricket">Cricket</option>
  </select>
</div>

Here sport_data is the array of list of sports . 这里sport_data是体育运动列表的数组。 Its not working fine . 它不能正常工作。 Is their any other way to set default value of select element? 他们还有其他设置select元素默认值的方法吗?

Should the select have a binding to the "sport" variable of the *ngFor? 选择是否应该绑定到* ngFor的“ sport”变量? In that case it seems that you have a typo, as you bind the ngModel to "sports" and not "sport". 在这种情况下,您似乎有错字,因为您将ngModel绑定到了“运动”而不是“运动”。 The code should look like this: 该代码应如下所示:

<div *ngFor="let sport of sport_data;" class="row">
  <select [(ngModel)]="sport.value" class="form-control">
      <option value="football">Sports</option>
      <option value="cricket">Cricket</option>
  </select>
</div>

As you asked for it, a different approach could be to use the (change) event on the select to set the value and the [selected] binding for the option to be selected. 根据您的要求,一种不同的方法可能是在select上使用(change)事件来设置值和要选择的选项的[selected]绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM