How to use an ngIf and ngFor on the same element: Angular structural directives explained
If you’ve developed an application using Angular, then you are familiar with the power of structural directives that Angular comes equipped with out of the box. During your development process, you might have ran into a situation where you have considered using two structural directives on the same element. That seems like a pretty straightforward solution but upon implementing, you will get the following error:
Template parse errors: Can't have multiple template bindings on one element.
Straightforward as it may seem, this error was thrown because Angular does not support this functionality, but does provide a solution.
So, what am I supposed to do now?
The key to this problem is the
Angular’s documentation recommends that when using any structural directive, you should place them on a root element.
ng-container is Angular’s way of giving you a logical root element to apply a structural directive.
Placing a structural directive on a root element is not a hard guideline to follow when using elements such as an
<li> will typically be the root element if you were to use the
*ngFor directive. However, this is not always the case.
Sometimes a root element isn’t available and a common solution would be to wrap the child elements in a div.
This is an acceptable solution most of the time but not always, as it can break the template appearance by conflicting with CSS rules and clutter the DOM (Document Object Model) with unnecessary tags (more on that later).
This is where ng-container element comes in.
<ul *ngIf="items" *ngFor="let item of items"> <li></li> </ul>
<ng-container *ngIf="items"> <ul *ngFor="let item of items"> <li></li> </ul> </ng-container>
What is a
ng-container in Angular?
element is a way to group elements together, but doing so without placing the
ng-container into the DOM.
ng-container out of the DOM solves any CSS conflicts that might arise.
ng-container is only recognized by Angular’s parser and it is not considered a component, directive, class, or interface.
You can click here to read the full documentation of ng-container’s as provided by the Angular team.