48

I have a situation where I need *ngIf and *ngFor directive on the same element. I found lot of answers on the stackoverlow but none for the this type of situation.

I have a table in which I'm looping through the array of objects and dynamically write cells in header:

 <table border="1" width="100%">
        <thead>
            <tr>
                <td *ngFor="let item of headerItems" *ngIf="item.visible">{{ item?.name }}</td>
            </tr>
        </thead>
        <tbody>
            ...
        </tbody>
    </table>

I want to show/hide if object contains visible set to true. How can I achieve this?

Igor Janković
  • 5,494
  • 6
  • 32
  • 46

4 Answers4

122

You can use the <ng-container> helper element for that.

<ng-container *ngFor="let item of headerItems" >
 <td *ngIf="item.visible">{{ item?.name }}</td>
</ng-container>

It is not added to the DOM.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Great answer. Thank you. Can you please explain a little bit what is exactly ng-container in this situation. I've used it for transclusion in components. – Igor Janković Nov 29 '16 at 08:31
  • 1
    It works just fine in case someone is having trouble with table tag. Another alternative is to replace table with a div tag – Junior Mayhé Jul 01 '17 at 17:23
  • Cool answer - all works. I just wanna jump in and say that this Ang 2 approach is complete bs lol. Y U DO THIS ANG? – Marko Jul 31 '17 at 19:00
  • @Marko no sure what you mean. Most people who complain about Angular didn't really try to understand what it is for. Angular 2 isn't a replacement for AngularJS, it's something new with a different goal. – Günter Zöchbauer Jul 31 '17 at 19:05
  • Yap, that coming from AngularJS expectation is probably the cause of my complains lol. Cause in AngJS, you could add multiple bindings. All though, doesn't it seem a bit too much that you have to add another element for each Ang 2 binding ... – Marko Jul 31 '17 at 19:15
  • 1
    When you understand what happens behind the scenes you can't imagine it being any other way ;-). Check the tutorials about structural directives. I haven't used AngularJS at all, therefore I didn't have very specific expectations. – Günter Zöchbauer Jul 31 '17 at 19:26
  • 1
    Works great, thanks! – El Dude Dec 17 '19 at 05:03
11

Günter Zöchbauer's answer is great. I've also found one more solution.

<td *ngFor="let item of headerItems" [hidden]="!item.visible">{{ item?.name }}</td>

But this one will be parsed inside html.

Igor Janković
  • 5,494
  • 6
  • 32
  • 46
3

You can use template element also:

<template ngFor let-item [ngForOf]="headerItems ">
   <td *ngIf="item.visible">{{ item?.name }}</td>
</template>

This will work for you.

Avnesh Shakya
  • 3,828
  • 2
  • 23
  • 31
1

You can also use ngclass for that

 .hidecell{
     display:none;
  }
<td *ngFor="let item of headerItems"  [ngClass]="{hidecell:item.isVisible}">
 {{ item?.name }}
</td>
Sriram
  • 739
  • 7
  • 18