I'd like to nest a loop in my angular template without nesting elements.
e.g. pseudocode:
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>
But this nests my divs. I'm trying to create a flat list, per:
<div myDirective>
{{title}}
</div>
<div myDirective>
{{content.text}}
</div>
<div myDirective>
{{content.text}}
</div>
<div myDirective>
{{title}}
</div>
<div myDirective>
{{content.text}}
</div>
etc...
Is this possible?
in this case you can use ng-container, you will write a nested code, but the output will not be nested.
<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>
From the Angular doc ng-container:
The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
I hope it may help you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With