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' }
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With