获取Angular中的选择选项的值

时间:2019-11-28 05:40:30

标签: javascript angular

我有这个user.model.ts,我有一个用户列表,我可以通过单击一个按钮来编辑该用户,该按钮过滤用户的数据并将其放入引导程序的模式中,在选择标签中可以使用[ngModel],我可以获取用户的国家/地区,但是当我更改国家/地区并提交表格时,我收到的是当前国家/地区而不是其ID,应该注意的是,当我在选项中使用[value]时,不会显示当前国家/地区,我可以获取值而不是名称吗?谢谢。

in 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>

4 个答案:

答案 0 :(得分:2)

您需要将[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>

也要加载默认值,有两个选项:

component.ts

ngOnInit(){
this.user['idCountry'] =  this.countries[0]['id']; //  set this after country data is loaded
}

OR

this.user['idCountry'] = '';

component.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>

答案 1 :(得分:2)

我认为您需要使用[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>

答案 2 :(得分:0)

您可以使用(更改)事件获取选定的值。

在您的html中:

<select (change)="onChange($event)"
   id="country"
   name="idCountry"
   class="form-control">
   <option *ngFor="let c of countries">{{ c.name }}</option>
</select>

在您的.ts中:

onChange(e: any) {
    console.log(e.target.value);
}

答案 3 :(得分:0)

您必须为您的选项标签设置[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)
  }