GoGo
GoGo

Reputation: 3057

How to retrieve id along with name when selected in Angular?

I have a select field that populates data as below. I populate data items as their names. My goal is to select data's name and their corresponded ids. Here is my HTML template:

<select class="custom-select d-block w-100" id="test" [(ngModel)]="record.firstName" #firstName="ngModel" name="firstName">
    <option value="">Choose...</option>
    <option *ngFor="let item of items" value="{{ item.name}}">{{ item.name }}</option>
</select>

When I select an item from the dropdown, record.firstName is set to item.name as expected. I was wondering how can I also retrieve item.id when I select the same item. I couldn't find a resource or tutorials to fix this. Any help will be appreciated!

Upvotes: 2

Views: 2243

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73741

Instead of setting the option values to item.name, you can set them to the item objects with [ngValue]. That will allow you to access any property of the selected item. If necessary, you can handle the ngModelChange event to do additional processing.

<select [(ngModel)]="selectedItem" (ngModelChange)="processSelectedItem($event)" ...>
    <option [ngValue]="undefined">Choose...</option>
    <option *ngFor="let item of items" [ngValue]="item">{{ item.name }}</option>
</select>

As an example, you could set record to a modified version of the selected item with:

processSelectedItem(item) {
    this.record.firstName = item.name;
    this.record.item_id = item.id;
}

Alternatively, you could bind the options to item.id (I assume that the id is unique), and set the record.firstName in the ngModelChange event handler:

<select [(ngModel)]="record.item_id" (ngModelChange)="processSelectedItem($event)" ...>
    <option value="-1">Choose...</option>
    <option *ngFor="let item of items" [value]="item.id">{{ item.name }}</option>
</select>

with:

processSelectedItem(itemId) {
    this.record.firstName = this.items.find(x => x.id === itemId).name;
}

Upvotes: 3

Related Questions