Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected object from "Select" in Angular2 without two-way data binding

Tags:

angular

I'm trying to create a dropdown with a list of objects. Due to the dropdown including other options it cannot be two-way binded to an array. On selection I want to pass the object to the component, but currently I can only pass the display value.

Here is my template:

    <select (change)="doSomething($event.target.value)">
        <option disabled selected>Please select...</option>
        <option *ngFor="let item of items" [ngValue]="item">{{ item.description }}</option>
        <option [ngValue]="">None of the above</option>
    </select>

And function in the component:

    doSomething(item) {
        console.log(item);
    }

This results in "Item description", rather than {'id': 4, .... how can I change this?

like image 650
Simeon Avatar asked Dec 23 '22 17:12

Simeon


1 Answers

<select [(ngModel)]="selectedValue" (change)="doSomething()">
    <option disabled selected>Please select...</option>
    <option *ngFor="let item of items" [ngValue]="item">{{ item.description }}</option>
    <option [ngValue]="">None of the above</option>
</select>

selectedValue: any;
doSomething() {
    console.log(this.selectedValue);
}

You can try with this idea.

like image 190
Thien Hoang Avatar answered Dec 28 '22 11:12

Thien Hoang