没有嵌套元素的 Angular4 模板中的嵌套循环

Nested loop in Angular4 template without nesting elements

我想在我的 angular 模板中嵌套一个没有嵌套元素的循环。

例如伪代码:

component.ts

let titles: string[];
let content: { title: string, text: string }[];

getContentByTitle(t: string) {
  return this.content.filter(c => c.title === t);
}

template.html

<div myDirective *ngFor="let title of titles">
 {{title}}
 <div myDirective *ngFor="content of getContentByTitle(title)">
  {{content.text}}
  </div>
</div>

但这嵌套了我的 div。我正在尝试创建一个平面列表,每个:

<div myDirective>
{{title}}
</div>
<div myDirective>
{{content.text}}
</div>
<div myDirective>
{{content.text}}
</div>
<div myDirective>
{{title}}
</div>
<div myDirective>
{{content.text}}
</div>
etc...

这可能吗?

使用ng-container

<div myDirective>
  <ng-container *ngFor='let o of objects'>
     {{o}}
  </ng-container>
</div>

它展开为:

<div myDirective>
  {{o}}{{o}}{{o}}{{o}}...
</div>

在这种情况下可以使用ng-container,你会写一个嵌套的代码,但是输出不会被嵌套。

<ng-container *ngFor="let title of titles">
  <div myDirective>
   {{title}}
  </div>
  <ng-container *ngFor="text of getContentByTitle(title)">
    <div myDirective>
      {{text}}
    </div>
  </ng-container>
</ng-container>

来自Angular doc ng-container:

Angular <ng-container> 是一个不影响样式或布局的分组元素,因为 Angular 没有将它放在 DOM 中。

希望对您有所帮助!