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?
Use ngFor and ngIf on same element It's very common scenario where we want to repeat a block of HTML using ngFor only when a particular condition is true. i.e., if ngIf is true.So in this case to use *ngIf and *ngFor on same element, place the *ngIf on a parent element that wraps the *ngFor element.
NgIf conditionally displays items by adding or removing them from the DOM depending on the condition. NgFor renders a list of items from iterable objects.
*ngIf and *ngFor can help you keep your Angular code clean, simple, and effective.
javascript - ng-if and ng-class-even/odd doesn't work well together and won't get expected outout - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
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.
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