获取Angular中选择选项的值

我有这个user.model.ts,我有一个用户列表,我可以通过单击过滤用户数据并将其置于引导模式中的按钮进行编辑,在选择标签中使用[ngModel]我可以获得国家我的用户,但是当我更改国家并提交表单时,我收到了当前国家,但没有收到它的 ID,应该注意的是,当我在选项中使用 [value] 时,它不会显示当前国家,我怎样才能得到值而不是名称?谢谢。


在 user.component.ts


updateUser(formActualizarTeam) {

  console.log(this.user);

}


在 user.model.ts


export class UserModel{

 name: string;

 idCountry: number;

}

在 user.component.html


<form

  #formUpdate="ngForm"

  (ngSubmit)="updateUser(formUpdate)">


<select

   id="country"

   name="idCountry"

   class="form-control"

   [(ngModel)]="user.idCountry">

   <option *ngFor="let c of countries">{{ c.name }}</option>

</select>


</form>


汪汪一只猫
浏览 243回答 3
3回答

饮歌长啸

我认为您需要使用该[value]属性来匹配要选择的选项ngModel那么代码将是(如果你有 idCountry国家数组)<select id="country" name="idCountry" class="form-control [(ngModel)]="user.idCountry">&nbsp; &nbsp;<option *ngFor='let c of countries' [value]='c.idCountry'>{{ c.name }}</option></select>

潇潇雨雨

您需要绑定[value]到idCountry,还需要设置默认值,所选值应与某些选项值匹配:<select&nbsp; &nbsp;id="country"&nbsp; &nbsp;name="idCountry"&nbsp; &nbsp;class="form-control"&nbsp; &nbsp;[(ngModel)]="user.idCountry">&nbsp; &nbsp;<option *ngFor="let c of countries" [value]="c?.idCountry">{{ c?.name }}</option></select>另外要加载默认值,还有两个选项:组件.tsngOnInit(){this.user['idCountry'] =&nbsp; this.countries[0]['id']; //&nbsp; set this after country data is loaded}或者this.user['idCountry'] = '';组件.html<select&nbsp; &nbsp;id="country"&nbsp; &nbsp;name="idCountry"&nbsp; &nbsp;class="form-control"&nbsp; &nbsp;[(ngModel)]="user.idCountry">&nbsp; &nbsp;<option value="" [disabled]="true"> Select country</option> // set some placeholder&nbsp; &nbsp;<option *ngFor="let c of countries" [value]="c?.idCountry">{{ c?.name }}</option></select>

守候你守候我

您必须为您的选项标签设置 [value],如下所示 [value]="c.idCountry"<form&nbsp; #formUpdate="ngForm"&nbsp; (ngSubmit)="updateUser(formUpdate)"><select&nbsp; &nbsp;id="country"&nbsp; &nbsp;name="idCountry"&nbsp; &nbsp;class="form-control"&nbsp; &nbsp;[(ngModel)]="user.idCountry">&nbsp; &nbsp;<option *ngFor="let c of countries" [value]="c.idCountry">{{ c.name }}</option></select></form>您现在将获得价值尝试打印它updateUser(ngform){&nbsp; &nbsp; console.log(ngform.form.value)&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript