Search code examples
htmlangularangular-ng-ifngforangular-material2

Nested *ngFor* with *ngIf


Problem

In the following code, I'm trying to display all Projects ( Objects ) under the Tab they're meant to go based on their category.

Category has to be equivalent.

EDIT: If that's not clear, take a look here.

Here's my code:

<md-tab-group>
    <md-tab *ngFor="let tab of tabs">

        <template md-tab-label>
            {{tab.name}}
        </template>

        <h1 *ngFor="let project of projects" *ngIf="tab.category == project.category">
            Project Name: {{project.name}}
        </h1>

    </md-tab>
</md-tab-group>

What I'm trying to achieve:

I'm trying to iterate through tabs and add each tab's name to the "template" of the tab.

Then, I'm trying to iterate through projects and if the project's category matches the tab's category, then it will be displayed under the tab.

Me

For some reason it doesn't seem to work. Am I doing something wrong ?
Excuse me and my logic, been awake for the past 2 days!


Solution

  • *ngIf and *ngFor (or in general more than one structural directive) on one element is not supported.

    You can use the helper element <ng-container> to apply *ngIf and *ngFor to two different elements without another element being added to the DOM

    <ng-container *ngFor="let project of projects">
      <h1 *ngIf="tab.category == project.category">
          Project Name: {{project.name}}
      </h1>
    </ng-container>
    

    See also *ngIf and *ngFor on same element causing error