Reputation: 23
How to get object value when changed select option
items = [
{
name:"Same",
age:14,
address:"Thailand"
},
{
name:"Peter",
age:30,
address:"Thailand"
}
]
<select class="custom-select" (change)="selectItem($event.target.value)">
<option *ngFor="let item of items" value="{{item}}" >
{{item.name}}
</option>
</select>
Can I use selectItem
to get Object value with
interface Person {
name: string;
age: number;
address: string;
}
public selectItem(data: Person) {
console.log('==> data:', data);
this.name = data.name;
this.age = data.age;
this.address = data.address
}
but my console.log is page: [object Object]
I want it to be page: {name:"Same" ,age:14 ,address:"Thailand"}
sometimes like that
Upvotes: 1
Views: 2261
Reputation: 5813
You need to us [ngValue] on your <option>
elements. When you use [value]
its binding to the elements value attribute which is a string, [ngValue]
allows you to bind an object.
You also need to add a binding model [ngModel]
and then bind to (ngModelChange)
event rather than (change)
. See stackblitz below for a working example...
<select class="custom-select" #sel [ngModel]="sel" (ngModelChange)="selectItem($event)">
<option *ngFor="let item of items" [ngValue]="item" >
{{item.name}}
</option>
</select>
https://trungk18.com/experience/angular-select-option-value-ngvalue/
Upvotes: 5
Reputation: 1536
Use Like following:
app.component.ts
public selectItem(data: any) {
data = JSON.parse(data);
console.log("==> data:", data);
this.name = data.name;
this.age = data.age;
this.address = data.address;
}
stringify(val: any) {
return JSON.stringify(val);
}
app.component.html
<select #sel class="custom-select" (change)="selectItem(sel.value)">
<option *ngFor="let item of items" value="{{stringify(item)}}" >
{{item.name}}
</option>
</select>
Working Example: https://stackblitz.com/edit/angular-ivy-cq8upg?file=src/app/app.component.html
Upvotes: 2