*ngIf and *ngFor on element [duplicate]

2020-01-29 07:47发布

问题:

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?

回答1:

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.



回答2:

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.



回答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.



回答4:

You can also use ngclass for that

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