Darkestlyrics
Darkestlyrics

Reputation: 310

Loop through JSON "Dictionary" returned from API (Typescript)

I make a call to an external API which returns a JSON string, I'm trying to get the data out of it and into an array of any. However whenever I make the call I get a single object with all the items as properties.

I'm trying to get all these into a <select> using NgOptions

I've been looking around to try and find an answer and have tried pushing to a temp array

What I have for the call method

    getCurrencies() {

        this.currService.getCurrencies(this.properties.APIKEY).subscribe((res: Response) =>
            this.currencies$ = res['results'],
            err => {
                console.log(err);
            }
        );

        console.log(this.currencies$);
    }

sample of what is returned

       {"ALL": { "currencyName": "Albanian Lek", "currencySymbol": "Lek", "id": "ALL" },
        "XCD": { "currencyName": "East Caribbean Dollar", "currencySymbol": "$", "id": "XCD" },
        "EUR": { "currencyName": "Euro", "currencySymbol": "€", "id": "EUR" },
        "BBD": { "currencyName": "Barbadian Dollar", "currencySymbol": "$", "id": "BBD" },
        "BTN": { "currencyName": "Bhutanese Ngultrum", "id": "BTN" }}

HTML for the <select>

         <select name='destination' class="form-control" id="CurrFrom" [(ngModel)]="destination"
                ng-options="item.id as item.currencyname for item in currencies$"></select>

Upvotes: 0

Views: 843

Answers (3)

Vaibhav
Vaibhav

Reputation: 1499

    <select name='destination' class="form-control" id="CurrFrom" [(ngModel)]="destination">
    <option *ngFor="for item in currencies$" [value]="item.id">{{item.currencyName}}</option>
</select>

you could do something like this and loop in on the object in options wrapped around select , hence dynamically populating options.

Upvotes: 0

nash11
nash11

Reputation: 8650

ng-options is an AngularJS directive. Instead, use ngFor in a normal option element along with the KeyValuePipe since your data is an object. By convention $ is used for Observables. For you, currencies$ is the data which is subscribed to your Observable so you can just rename it as currencies.

Here is how your template will now look.

<select name='destination' class="form-control" id="CurrFrom" [(ngModel)]="destination">
    <option *ngFor="let currency of currencies | keyvalue" [value]="currency.value.id">{{currency.value.currencyName}}</option>
</select>

Here is a working example on StackBlitz.

Upvotes: 1

Shahid Islam
Shahid Islam

Reputation: 629

select control

       <select id="test2" name="test2" formControlName="test2"
 class="form-control select-height" [(ngModel)]="selectedValue" placeholder="currency">
                          <option *ngFor="let item of items" [value]="item.typeId">{{item.title}}</option>
                        </select>

Upvotes: 0

Related Questions