helenDeveloper
helenDeveloper

Reputation: 732

How get the selected item in option angular

I have a dropdown that fills with some item of type ObjectA.

item.component.html:

<label>items list:
    <select formControlName="itemsCtl" (change)="onChange()">
        <option *ngFor="let item of itemList" [value]="item">{{item.label}}</option>
    </select>
</label>

In my reactive forms I need to have the selected item but when I searched a lot on the Internet I found the code for my purpose:

item.component.ts:

selectedItem : ObjectA;
...
onChange()
{  
    this.selectedItem = this.factorForm.controls['itemsCtl'].value;
}

but when I get the selected item it is as [object object] while I need to have selected item as ObjectA. how I can have selected item as ObjectA or even how I can convert [object object] to ObjectA?

Using Angular 5.0.1.

Upvotes: 2

Views: 6214

Answers (2)

yash_DedSec
yash_DedSec

Reputation: 251

Well I am not really sure about what is the structure of your (itemList) or your (ObjectA)

For that I need a little bit more information.

Instead if your method is not working try this:

<label>items list:
<select formControlName="itemsCtl" (change)="onChange()" [(ngModel)]="someVar">
    <option *ngFor="let item of itemList" [value]="item">{{item.label}}</option>
</select>

Then in your function:

selectedItem : ObjectA;
someVar: any;
...
onChange()
{  
    this.selectedItem = this.factorForm.controls['itemsCtl'].value;
    console.log(someVar);
}

See what output this gets.

Hope all this helps!

Upvotes: 0

Oleksandr Poshtaruk
Oleksandr Poshtaruk

Reputation: 2146

Try to use ngValue directive instead of value.

    <option  *ngFor="let item of itemList"  [ngValue]="item"   >{{item.label}}</option>

Upvotes: 1

Related Questions