Reputation: 766
I am using angular 4 and spring boot,i get all the record as a List from spring boot to angular 4 but in the angular form i get only single object data,how to list multiple values in Search box?
component.ts: In this component i am getting all the values but display single data!
characters=[]; chars=[];
ngOnInit() {
this.drugservice.getval().subscribe(
data => {
this.chars.data,
this.characters = [
{value: data[0].id},
{label: data[0].name}
],
alert(data[0].name)
},
err => {
console.log('Error Occured ');
});
}
ang.html:
<div class="col-sm-12 col-xl-4">
<ng-select [ngClass]="'ng-select'" [options]="characters" formControlName="selectedCharacter"></ng-select>
</div>
Back end rerun Object Values:
[
{
"id": 1,
"name": "ak"
},
{
"id": 2,
"name": "java"
}
]
Upvotes: 0
Views: 3312
Reputation: 44685
There are several issues with your code, most of them within the subscribe()
handler. First of all, the commas are making it very strange, but I guess that you're trying to do this:
this.drugservice.getval().subscribe(data => {
this.chars.data, this.characters = [{value:data[0].id},{label:data[0].name}];
alert(data[0].name);
});
One issue with this code is that you only use data[0]
, so if data
contains multiple objects, you're only doing something with the first object. Probably, you want to do something like this:
this.drugservice.getval().subscribe(data => {
this.characters = data.map(obj => ({ value: obj.id, label: obj.name }));
});
Or a more reactive way to do this would be:
this.drugservice
.getval()
.map(data => data.map(obj => ({ value: obj.id, label: obj.name })))
.subscribe(data => this.characters = data);
By using the map()
operator you can map all objects in the data
array to the { value: ..., label: ... }
structure.
And last but not least, if you're using ng-select, you should probably bind to items
rather than to options
:
<ng-select [ngClass]="'ng-select'" [items]="characters"
formControlName="selectedCharacter">
</ng-select>
But according to the documentation of ng-select, you don't need to map your objects to a certain structure as long as you provide the correct bindValue
property, so you might want to take a look into that.
Upvotes: 2