如何在Angular2中动态显示键对应的值?
Got it, let's break this down step by step so you can show those key-value pairs dynamically without hardcoding each field.
First, let's tweak your component code to properly grab the keys from your list items. Since your API returns consistent items (like each has id and title), we can get the keys from the first item once your data loads:
viewPage(page, per_page){ this._adminPage.fetchAdminPageData(page, per_page).subscribe( data => { this.list = data.list; this.total_item = data.total; this.current_page = data.current_page; // Grab keys from the first item if the list isn't empty this.arrayOfKeys = this.list.length ? Object.keys(this.list[0]) : []; } ); }
Now, over in your component's HTML template, use nested *ngFor loops to iterate through each item in your list, then loop through the keys to display each key and its corresponding value:
<!-- Wrap in a div to check if list has items (optional but safe) --> <div *ngIf="list.length" class="data-container"> <!-- Loop through each item in the list --> <div *ngFor="let item of list" class="data-item"> <!-- Loop through each key we stored --> <div *ngFor="let key of arrayOfKeys" class="key-value-row"> <strong>{{ key }}:</strong> {{ item[key] }} </div> <hr> <!-- Add a line between items for clarity --> </div> </div> <!-- Show a message if list is empty --> <div *ngIf="!list.length">No data available</div>
What if items have different keys?
If some items in your list might have unique keys, you can create a quick method in your component to get keys for each individual item instead of using a single arrayOfKeys:
// Add this method to your component class getItemKeys(item: any): string[] { return Object.keys(item); }
Then update your template to use this method:
<div *ngIf="list.length" class="data-container"> <div *ngFor="let item of list" class="data-item"> <div *ngFor="let key of getItemKeys(item)" class="key-value-row"> <strong>{{ key }}:</strong> {{ item[key] }} </div> <hr> </div> </div>
Quick styling tip
You can add some CSS to make the key-value pairs look cleaner, like:
.key-value-row { margin: 8px 0; } .data-item { padding: 12px; border: 1px solid #eee; border-radius: 4px; margin-bottom: 16px; }
That should do it! This way, no matter what keys come back from your API, they'll automatically show up in your component without you having to update the template every time.
内容的提问来源于stack exchange,提问作者Saswat

