[英]Displaying keys and values from a list of object in angular typescript
在我的 angular 應用程序中,我有一個從 API 動態獲取的對象列表,例如:
[
{
"_id": "some id",
"DATE": "2021/01/08",
"COUNT": "23",
"AMOUNT": "268710"
},
{
"_id": "some id",
"DATE": "2021/09/18",
"COUNT": "2",
"AMOUNT": "1,167.73"
}
]
我希望能夠在不明確提及的情況下訪問每個 object 的鍵和值,這樣如果我得到一個包含更多對象或不同鍵的列表,我也可以顯示它們,我該怎么做?
<tr
*ngFor="
let row of FilteredMatchTransactions
| paginate
: { itemsPerPage: itemsPerPage, currentPage: p };
let i = index
"
>
<td>
{{ KeysFilteredMatchTransactions[1] }} :
{{ row.DATE}}
</td>
<td>
{{ KeysFilteredMatchTransactions[2] }} : {{ row.COUNT}}
</td>
<td>
{{ KeysFilteredMatchTransactions[3] }} :
{{ row.AMOUNT}}
</td>
</tr>
TS:
ngOnInit(): void {
const Param = this.route.snapshot.queryParamMap.get('_id');
this._crudService.GetReportById(Param).subscribe((res) => {
this.MatchTransactions = res;
this.FilteredMatchTransactions = this.MatchTransactions.onlyInFile1;
this.KeysFilteredMatchTransactions = Object.keys(
this.FilteredMatchTransactions[0]
);
console.log(this.KeysFilteredMatchTransactions);
});
您可以使用 Angular 鍵值keyvalue
遍歷 object 的每個屬性。嘗試以下操作
Controller (*.ts)
ngOnInit(): void {
const Param = this.route.snapshot.queryParamMap.get('_id');
this._crudService.GetReportById(Param).subscribe((res) => {
this.MatchTransactions = res;
this.FilteredMatchTransactions = this.MatchTransactions.onlyInFile1;
});
}
模板 (*.html)
<tr
*ngFor="let row of FilteredMatchTransactions |
paginate : { itemsPerPage: itemsPerPage, currentPage: p };
let i = index"
>
<ng-container *ngFor="let transaction of row | keyvalue">
<td *ngIf="transaction.key !== '_id'">
{{ transaction.key }} : {{ transaction.value }}
</td>
</ng-container>
</tr>
更新:
FilteredMatchTransactions
->第二row
*ngFor
。*ngIf
檢查key !== '_id'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.