html - 如何在 Angular 中使用 ngFor 设置选择下拉菜单中的第一项
问题描述
我在下面有这个下拉列表,其中包含所有国家/地区,但不显示第一个值(“美国”)。我怎样才能让第一个项目成为选定的项目?
如果 index = 0,是否可以有一个条件语句设置'selected'?我知道两个绑定是不可能的,但我正在寻找其他选择。
<div class="form-group">
<select id="country" class="form-control" formControlName="countryList">
<option *ngFor="let country of countryList;" value={{country}}>
{{country}}
</option>
</select>
</div>
以下是我在页面中看到的内容。最初没有选择任何项目。在我选择某些东西之前它是空白的!
更新 - 我在下面尝试这个,但它似乎也不起作用。
[value]="country"
[selected]="country == 'United States' ? true : null"
CountryList 看起来像这样
export class Countries {
countryList: string[] = ['United States', 'Afghanistan', 'Albania'];
CountryList() {
return this.countryList;
}
}
// to initialize it, in my component I do this
countryList: string[] = new Countries().countryList;
解决方案
从 countryList 为您想要的 formControl 分配初始值。
例如:- controlModel.controls['countryList'].setValue('United States');
推荐阅读
- python-3.x - Python:3 - 在找到关键字后将字符串设为变量?
- kentico - 如何在 Kentico 中用文档名称设置页面标题?
- html - 如何用css取消一个项目
- authentication - 是否可以使用与 apiserver 请求关联的“额外”属性来使用 RBAC 做出授权决策?
- java - 使用 MediaPlayer 时,显示“E/ExtMediaPlayer-JNI: env->IsInstanceOf failed”错误。如何解决?
- java - 如何使用值从 HashMap 中删除键
- php - WooCommerce 自定义字段未显示在电子邮件或订单信息中
- node.js - 生成网页的 PDF
- yii2 - yii2,将现有的 unix 值转换为查询中的时间戳
- mysql - 使用 sequelize 连接到 aws rds 时连接被拒绝