Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop-down change -data showing [object object]

am trying to bind JSON data to a drop-down list.OnChnge function I pass the value to the corresponding component, when I debug it showing [object object].

My JSON value

dataLists = [
    { 'id': 1, 'host_name': 'Service 1', 'port': '8090', 'username': 'user1', 'password': 'abc' },
    { 'id': 2, 'host_name': 'Service 1', 'port': '8090', 'username': 'user2', 'password': 'abc' },
    { 'id': 3, 'host_name': 'Service 1', 'port': '8090', 'username': 'user3', 'password': 'abc' }
];

html code

<select #selectedData (change)="selected($event,selectedData.value)">
            <option>Select....</option>
            <option *ngFor="let dataList of dataLists"  [value]="dataList">{{dataList.host_name}}</option>
        </select>

component code

selected(ev: Event, data: any []) {
        // console.log('data', data);
        for (const ea of data) {
            console.log(ea);

        }

How can i get data as json format in component. like { 'id': 1, 'host_name': 'Service 1', 'port': '8090', 'username': 'user1', 'password': 'abc' }

like image 730
arj Avatar asked Oct 30 '25 04:10

arj


1 Answers

By default, value property accepts string value(converting object into a string would results [object object]). To use the object as value use ngValue property which accepts any type as the value.

<option *ngFor="let dataList of dataLists"  [ngValue]="dataList">{{dataList.host_name}}</option>

Final code would be like:

Template:

<select #selectedData (change)="selected($event,selectedData.value)">
  <option>Select....</option>
  <option *ngFor="let dataList of dataLists" [ngValue]="dataList">{{dataList.host_name}}</option>
</select>

TS:

selected(ev: Event, data: any) {
  console.log(data);
}
like image 152
Pranav C Balan Avatar answered Nov 01 '25 20:11

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!