theShadow89
theShadow89

Reputation: 1549

Angular 4 - show/Hide elements on ngFor directive

I have a list of lists and I want to hide/show internal list based on an attribute value

<md-list *ngFor="let el of data">
    <md-list-item *ngFor="let item of el.items" >
      <h4 mdSubhead]er>{{item.name}}</h4>
    </md-list-item>h4
  </md-list>

I have tried with *ngIf, but Angular4 permit only one template binding for an element.

How can I implement this beavior?

Upvotes: 0

Views: 4845

Answers (4)

Sajeetharan
Sajeetharan

Reputation: 222582

You can just do by adding a extra div with a condition or ng-container which would be the best for angular

<md-list *ngFor="let el of data">
  <ng-container *ngIf="el.something">
    <md-list-item *ngFor="let item of el.items" >
      <h4 mdSubheader>{{item.name}}</h4>
    </md-list-item>
  </ng-container>
 </md-list>

Upvotes: 3

Sasidhar Vanga
Sasidhar Vanga

Reputation: 3404

Use <ng-container> as mentioned here : <ng-container> to the rescue

<md-list *ngFor="let el of data">
    <ng-container *ngIf="your-condition-here">
        <md-list-item *ngFor="let item of el.items" >
            <h4 mdSubhead]er>{{item.name}}</h4>
        </md-list-item>
    </ng-container>
</md-list>

Upvotes: 0

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

I think best way might be to get data before, then remove unneeded items and iterate through remaining lists. But if really need in template, so you can use ng-template and long *ngFor version, so something like:

<ng-template ngFor let-el [ngForOf]="data" let-i="index">
 <md-list #el>
 <ng-template ngFor let-item [ngForOf]="el.items" let-i="index">
  <md-list-item #item>
    </md-list-item>h4
  </ng-template>
 </md-list>
</ng-template>

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Use ng-container (no need of extra element) and on the same use *ngIf to hide/show DOM conditionally.

<md-list *ngFor="let el of data">
  <ng-container *ngIf="el.show">
    <md-list-item *ngFor="let item of el.items" >
      <h4 mdSubhead]er>{{item.name}}</h4>
    </md-list-item>
  </ng-container>
</md-list>

Upvotes: 2

Related Questions