使用数据集选项填充垫选择



我正在尝试用从API获得的数据集填充mat-select下拉列表。具体地说,数据是rates对象的一部分。

这是我的代码

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>

我目前只在选择列表中看到[object Object]

您看到的是[object object],因为currencies属性是一个对象数组。此外,看起来你想在ngFor the currencies.rates属性中循环,而不仅仅是currencies对象。即使如此,你也会遇到问题,因为currencies.rates中的每个项目都有不同的属性密钥。如果你在下面写,第一个速率会显示良好,但第二个速率不会正确显示。

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

如果你对后端有一定的控制权,那么更好地将数据结构为可能是有意义的

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

这将使您的模板更易于阅读和编写。

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

最新更新