How to use ngIf without an extra element in Angular2?

In order to use *ngIf without an extra element in Angular 2+, we can use either <ng-container> or <ng-template>
But in many cases, <ng-container> is recommended.
The best scenario regarding the usage of with *ngIf without an extra element is mentioned below.

app.component.ts:

filter_none

edit
close

play_arrow

link
brightness_4
code

import { Component } from '@angular/core';
@Component({
  selector: 'my-app-table',
  template: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  
India=[{city:'Hyderabad'}, {city:'Mumbai'}]
  
}

chevron_right


app.component.html :

filter_none

edit
close

play_arrow

link
brightness_4
code

<h1>ng-container example</h1>
  
 <div *ngFor="let state of India"
   <ng-container *ngIf="state.city">
      <p> {{ state.city }} </p>
   </ng-container>
 </div>

chevron_right


Illustration of above code for ng-container

If we inspect it then  we can see there is no extra element added after <div> tag and before <p> tag.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.