You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular4模板中实现嵌套循环但不生成嵌套元素

To get a flat list of <li> elements instead of nested <div>s, you’ll want to flatten your data structure first in the component, then use a single *ngFor loop in the template. This avoids nested elements and also improves performance (since calling getContentByTitle() directly in the template can trigger unnecessary re-runs on every change detection cycle).

Step 1: Update the Component to Create a Flat Combined List

Add a computed getter that merges your titles and their corresponding content into a single flat array. Each item will have a type flag to distinguish between titles and content entries:

import { Component } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  titles: string[] = ['Title 1', 'Title 2']; // Example data
  content: { title: string, text: string }[] = [
    { title: 'Title 1', text: 'Content for Title 1' },
    { title: 'Title 1', text: 'More content for Title 1' },
    { title: 'Title 2', text: 'Content for Title 2' }
  ];

  // Getter to create a flat list of titles + content
  get flatContentList(): Array<{ type: 'title' | 'content', data: string | { text: string } }> {
    const flatList: Array<{ type: 'title' | 'content', data: any }> = [];
    
    this.titles.forEach(title => {
      // Add the title entry
      flatList.push({ type: 'title', data: title });
      
      // Add all corresponding content entries
      const matchingContent = this.content.filter(c => c.title === title);
      matchingContent.forEach(contentItem => {
        flatList.push({ type: 'content', data: contentItem });
      });
    });
    
    return flatList;
  }
}

Step 2: Update the Template for Flat <li> Elements

Now use a single *ngFor loop over the flat array to generate your list. You can conditionally render the content based on the item type, and apply your myDirective to each <li>:

<ul>
  <li 
    *ngFor="let item of flatContentList"
    myDirective
  >
    {{ item.type === 'title' ? item.data : item.data.text }}
  </li>
</ul>

Bonus: Style Titles Differently (Optional)

If you need to visually distinguish titles from content, add a conditional class:

<li 
  *ngFor="let item of flatContentList"
  myDirective
  [class.title-item]="item.type === 'title'"
>
  {{ item.type === 'title' ? item.data : item.data.text }}
</li>

Then add corresponding CSS:

.title-item {
  font-weight: bold;
  font-size: 1.1rem;
  /* Add any other styling for titles */
}

Why This Works:

  • Flat Structure: The flatContentList getter creates a single array where each title is followed immediately by its content items. This means the *ngFor loop generates all <li> elements at the same level with no nesting.
  • Performance: Precomputing the flat list avoids calling filter() on every change detection cycle (a common pitfall when using component methods directly in templates).
  • Maintainability: All data manipulation stays in the component, keeping the template focused on rendering logic.

内容的提问来源于stack exchange,提问作者xiience

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:24:49