'Populate mat-select with data set option

I am trying to populate a mat-select dropdown with a data set that I get from an API. Specifically the data that part of the rates object.

Here is my code

  public currencies: Object[] = [];

  getCurrencies() {
    this.currencyService.currencyRates().subscribe({
      next: (v) => {
        this.currencies = [v.rates];
        console.log(this.currencies);
      },
      error: (e) => console.error(e),
      complete: () => console.info('complete') 
   });
  }

  //this.currencies looks like below
  this.currencies = [{
           "success":true,
           "timestamp":1645213266,
           "base":"EUR",
           "date":"2022-02-18",
           "rates":{
              "AED":4.162629,
              "AFN":104.263296,
              "ALL":121.070058
           }
   }]


   <mat-form-field appearance="fill">
            <mat-label>Select an option</mat-label>
            <mat-select >
              <mat-option>None</mat-option>
              <mat-option *ngFor="let item of currencies" [value]="item">{{item}}</mat-option>
            </mat-select>
   </mat-form-field>

I currently just see [object Object] in the select list



Solution 1:[1]

You're seeing [object Object] because the currencies property is an array of objects. In addition, it looks like you'd want to loop over in your ngFor the currencies.rates property, as opposed to just the currencies object. Even still, you'll hit a problem as each item in the currencies.rates has different property keys. If you wrote below, the first rate would show fine, but the second rate wouldn't show properly.

<mat-option *ngFor="let item of currencies?.rates" [value]="item">{{item.AED}}</mat-option>

If you had some control over the backend, it might make sense to better structure your data to look something like :

{ 
"rateName": "AED", 
"rateAmt": 4.162629 
}

This would make your template much easier to read and write.

<mat-option *ngFor="let item of currencies?.rates" [value]="item">{{item.rateName}} - {{item.rateAmt}}</mat-option>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tylerherzog