Issue
In my Angular-12, I have this JSON response from the API endpoint:
{
"message": "vehicle Model Detail.",
"error": false,
"code": 200,
"results": {
"vehiclemakes": [{
"name": "Freightliner",
"id": 15
},
{
"name": "Honda",
"id": 13
},
{
"name": "Renault",
"id": 3
},
{
"name": "Suzuki",
"id": 16
},
{
"name": "Toyota",
"id": 4,
},
{
"name": "Volkswagen",
"id": 6
},
{
"name": "Volvo",
"id": 5
}
]
}
}
Service:
public getParameters(): Observable<any> {
return this.http.get(this.api.baseURL + 'parameters', this.httpOptions);
}
Component:
vehicles!: any[];
loadAllVehicles() {
this.vehiclemodelService.getParameters().subscribe(
data => {
this.vehicles = data.results.vehicles;
},
error => {
this.store.dispatch(loadErrorMessagesSuccess(error));
}
);
}
ngOnInit(): void {
this.loadAllVehicles();
}
I am to load this in a dropdown select list:
HTML:
<ng-select [items]="vehicles"
[selectOnTab]="true"
[searchable]="true"
bindValue="name"
bindLabel="make_id"
placeholder="Select Vehicle Make"
[multiple]="false"
[clearable]="true"
required
formControlName="make_id">
</ng-select>
When I loaded the form and click on the select dropdown list, it appears that data is there but it displays nothing.
How do I get this sorted out?
Thanks
Solution
Issues
As @Nenad mentioned,
results.vehiclesis not valid in your JSON. You have to useresults.vehiclemakes.make_idis not valid in the object ofvehiclemakes. Meanwhile,bindLabelproperty is used to display the label, whilebindValueis used for value. With existing code, the generated options will display id as label with the name as value.
<ng-select bindValue="name"
bindLabel="make_id">
</ng-select>
Solution
- Assign
vehicleswithdata.results.vehiclemakes. - Set
bindLabelwithnameandbindValuewithid.
.component.ts
loadAllVehicles() {
this.vehiclemodelService.getParameters().subscribe(
data => {
this.vehicles = data.results.vehiclemakes;
},
error => {
this.store.dispatch(loadErrorMessagesSuccess(error));
}
);
}
.component.html
<ng-select [items]="vehicles"
[selectOnTab]="true"
[searchable]="true"
bindValue="id"
bindLabel="name"
placeholder="Select Vehicle Make"
[multiple]="false"
[clearable]="true"
required
formControlName="make_id">
</ng-select>
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.