3 回答
TA贡献1951条经验 获得超3个赞
我认为您需要使用该[value]属性来匹配要选择的选项ngModel
那么代码将是(如果你有 idCountry国家数组)
<select id="country" name="idCountry" class="form-control [(ngModel)]="user.idCountry">
<option *ngFor='let c of countries' [value]='c.idCountry'>{{ c.name }}</option>
</select>
TA贡献1833条经验 获得超4个赞
您需要绑定[value]到idCountry,还需要设置默认值,所选值应与某些选项值匹配:
<select
id="country"
name="idCountry"
class="form-control"
[(ngModel)]="user.idCountry">
<option *ngFor="let c of countries" [value]="c?.idCountry">{{ c?.name }}</option>
</select>
另外要加载默认值,还有两个选项:
组件.ts
ngOnInit(){
this.user['idCountry'] = this.countries[0]['id']; // set this after country data is loaded
}
或者
this.user['idCountry'] = '';
组件.html
<select
id="country"
name="idCountry"
class="form-control"
[(ngModel)]="user.idCountry">
<option value="" [disabled]="true"> Select country</option> // set some placeholder
<option *ngFor="let c of countries" [value]="c?.idCountry">{{ c?.name }}</option>
</select>
TA贡献1802条经验 获得超10个赞
您必须为您的选项标签设置 [value],如下所示 [value]="c.idCountry"
<form
#formUpdate="ngForm"
(ngSubmit)="updateUser(formUpdate)">
<select
id="country"
name="idCountry"
class="form-control"
[(ngModel)]="user.idCountry">
<option *ngFor="let c of countries" [value]="c.idCountry">{{ c.name }}</option>
</select>
</form>
您现在将获得价值尝试打印它
updateUser(ngform){
console.log(ngform.form.value)
}
添加回答
举报