How to use an ngIf and ngFor on the same element: Angular structural directives explained

Posted by Bashar Fadil in spotlight Angular

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 ng-container. Angular’s documentation recommends that when using any structural directive, you should place them on a root element. The 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 <ol> or <ul>. The <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.

The Error:

<ul *ngIf="items" *ngFor="let item of items">

The Fix:

<ng-container *ngIf="items">
  <ul *ngFor="let item of items">

What is a ng-container in Angular?

The ng-container element is a way to group elements together, but doing so without placing the ng-container into the DOM. Leaving the ng-container out of the DOM solves any CSS conflicts that might arise. The 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.

spotlight Angular

Sign up to receive updates about future posts from Logicdrop