1
votes

i have this user.model.ts, Ihave a list of users that I can edit by clicking on a button that filters the user's data and puts it in a modal of bootstrap, with the [ngModel] in select tag i can get the country of my user but when i change the country and submit the form I receive the current country but not its id, it should be noted that when I use [value] in the option it does not show me the current country, how can i get the value and not the name? Thanks.

in user.component.ts

updateUser(formActualizarTeam) {
  console.log(this.user);
}

in user.model.ts

export class UserModel{
 name: string;
 idCountry: number;
}

in 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
can you show the countries array.,?Ganesh

4 Answers

2
votes

I think you need to use the [value] attribute to match the options to select ngModel

then the code will be (if you have idCountry in countries array)

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

You need bind [value] to idCountry , also to set default value the selected value should match some option value :

<select
   id="country"
   name="idCountry"
   class="form-control"
   [(ngModel)]="user.idCountry">
   <option *ngFor="let c of countries" [value]="c?.idCountry">{{ c?.name }}</option>
</select>

Also to load the default value there are two option:

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>
0
votes

You have to set [value] for your option tag like below [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>

you will get value now try priting it

updateUser(ngform){
    console.log(ngform.form.value)
  }
0
votes

You can get selected value by using (change) event.

In your html:

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

In you .ts:

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