Using ngIf without an extra element in Angular 2

HtmlTemplatesAngular

Html Problem Overview


Can I use ngIf without an extra container element?

<tr *ngFor="...">
  <div *ngIf="...">
    ...
  </div>
  <div *ngIf="!...">
    ...
  </div>
</tr>

It doesn't work in a table because that would make invalid HTML.

Html Solutions


Solution 1 - Html

ng-container is preferred over template:

<ng-container *ngIf="expression">

See:

https://stackoverflow.com/questions/39547858/angular-2-ng-container

https://github.com/angular/angular.io/issues/2303

Solution 2 - Html

I found a method for that on: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#star-template.

You can simply use the <template> tag and replace *ngIf with [ngIf] like this.

<template [ngIf]="...">
  ...
</template>

Solution 3 - Html

You can't put div directly inside tr, that would make invalid HTML. tr can only have td/th/table element in it & inside them you could have other HTML elements.

You could slightly change your HTML to have *ngFor over tbody & have ngIf over tr itself like below.

<tbody *ngFor="...">
  <tr *ngIf="...">
    ...
  </tr>
  <tr  *ngIf="!...">
    ...
  </tr>
  ..
</tbody>

Solution 4 - Html

adding brackets resolves this issue

 <ng-container *ngIf="(!variable| async)"></ng-container>

Solution 5 - Html

You can try this:

<ng-container *ngFor="let item of items;">
    <tr *ngIf="item.active">
        <td>{{item.name}}</td>
    </tr>
 </ng-container>
 

Here, I have iterate loop in ng container so it will not create extra dom and later in tr tag check condition if I want to render or not.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjanispritzkauView Question on Stackoverflow
Solution 1 - HtmlAlexander TaylorView Answer on Stackoverflow
Solution 2 - HtmljanispritzkauView Answer on Stackoverflow
Solution 3 - HtmlPankaj ParkarView Answer on Stackoverflow
Solution 4 - HtmlSourabh ShahView Answer on Stackoverflow
Solution 5 - HtmlJitendraView Answer on Stackoverflow