kianoush
kianoush

Reputation: 85

get tow value from dropdown

I have this code for dropdown in edit form:

    <select id="inputState"  class="form-control" [(ngModel)]="seletRoleId"  formControlName="roleName">
      <option *ngFor="let item of roleList" seletRoleId="item.id" [value]="item.name"> {{item.name}}
      </option>
    </select>

But I need to get item.name and item.id.

This code [value]="item.name" for show user RoleName for edit.

How can I get tow value id and name from the dropdown?

Upvotes: 1

Views: 77

Answers (2)

R3tep
R3tep

Reputation: 12854

You can use an object instead, like that you can get the name and the id

<option ... [value]="{name: item.name, id: item.id} | json"> 

You can parse the result to get a proper object after.

Simple example

changeConsole() {
  console.log(JSON.parse(this.selectRole).id);
  console.log(JSON.parse(this.selectRole).name);
}
<select [(ngModel)]="selectRole" (change)="changeConsole()">
  <option [value]="{name: 'toto', id: 11} | json"> yo 11
  </option>
  <option [value]="{name: 'titi', id: 13} | json"> yo 13
  </option>
</select>

Upvotes: 1

dev-dan
dev-dan

Reputation: 6283

You could attach a click so that each time an option is clicked it sends the item to a function. Then in the function you have access to the entire item.

<option *ngFor="let item of roleList" seletRoleId="item.id"
(click)=getDetails(item) [value]="item.name"> 
  {{item.name}}
 </option>

Then in your controller a function looking like so would allow you to do as you wish with the item. Store it as Component Variable or do the work you need in the function.

public currentSelection;

public getDetails(item): void
{
    this.currentSelection = item;

    console.log(item.id);
    console.log(item.name);
}

Upvotes: 1

Related Questions