💉 Shot #6: How to apply multiple *ngIf/*ngFor statements to an element
Introduction
Have you ever been in a situation when you need to apply *ngFor
and *ngIf
to a single element? If yes, then you should know that this is unfortunately not possible in Angular.
Let’s imagine that we need to render a list of product names, but should exclude products that are out of stock:
In this case, we are adding additional span
element, since we cannot have two structural directives at the same element.
Shot
Fortunately, Angular provides us with a special kind of element, called <ng-container>
. It won’t be rendered into the resulting DOM, allowing us to group elements together to apply structural directives to them:
This is especially useful, in a case we cannot have additional elements, for example, rendering <option>
elements inside of <select>
element: