Angular/TypeScript中Google Charts动态化实现求助(新手)
Absolutely! You can definitely generate this data dynamically using a loop—this approach is way cleaner, more maintainable, and scalable compared to hardcoding each row manually, especially if your dataList grows in size later. Let’s break down two common scenarios based on your needs:
Scenario 1: Maintain Your Specific Row Order
If you need to keep the exact row sequence you’re using now (0 → 3 → 1 → 2), you can define an array of desired indices and loop through that to build your chart data:
// Define the order of indices you want to use const desiredIndices = [0, 3, 1, 2]; // Initialize with your chart header const chartData = [['Encounter Type', 'No of Encounters']]; // Loop through the indices to populate data rows desiredIndices.forEach(index => { const [encounterType, encounterCount] = this.dataList[index]; chartData.push([encounterType, encounterCount]); }); // Convert to Google Charts data table const data = google.visualization.arrayToDataTable(chartData);
This way, if you ever need to adjust the row order later, you just update the desiredIndices array instead of rewriting multiple lines of code.
Scenario 2: Use All Items in dataList
If you want to include every entry from dataList without a specific order, you can directly loop through the entire array. Here’s a couple of clean ways to do this:
Basic Loop Approach
const chartData = [['Encounter Type', 'No of Encounters']]; // Iterate over every item in dataList this.dataList.forEach(item => { chartData.push([item[0], item[1]]); }); const data = google.visualization.arrayToDataTable(chartData);
Concise Array Spread + Map
For a more streamlined one-liner (great if you prefer functional-style code):
const chartData = [ ['Encounter Type', 'No of Encounters'], ...this.dataList.map(item => [item[0], item[1]]) ]; const data = google.visualization.arrayToDataTable(chartData);
Quick Tips to Avoid Issues
- Ensure
this.dataListis initialized: Run this code after your data has loaded (e.g., inngOnInitafter an API call resolves) to preventundefinederrors. - Add validation (optional): If
dataListmight contain incomplete or null entries, add a check to skip invalid items:this.dataList.forEach(item => { // Only add the row if the item exists and has both required values if (item && item.length === 2) { chartData.push([item[0], item[1]]); } });
内容的提问来源于stack exchange,提问作者Sitansu




