ng-container
ng-container
in Angular is a structural directive in Angular that allows you to create groups of elements without adding an additional node to the DOM. This is useful when you need to apply a directive or use conditionals or loops *ngFor
for a group of elements, but do not add unnecessary tags to the markup.
ng-container
is not a component and does not create its own instance, so it cannot be accessed through ViewChild
or ContentChild
. It simply acts as a container for the elements you want to group. Therefore, instead of using
And now to the examples ng-container
:
Conditional display of elements
you can use ng-container
to group elements that should be shown or hidden together. For example:
<ng-container *ngIf="isLoggedIn">
<h1>Welcome, {{ user.name }}!</h1>
<p>You are now logged in.</p>
<button (click)="logout()">Logout</button>
</ng-container>
In this example ng-container
used to group elements h1
, p
And button
. If isLoggedIn
equals true
then all the elements inside ng-container
will be displayed on the page. Otherwise, they will not be displayed.
Usage
*ngFor
you can use ng-container
to group elements that should be created using *ngFor
. For example:
<ng-container *ngFor="let item of items">
<h2>{{ item.title }}</h2>
<p>{{ item.description }}</p>
</ng-container>
In this example ng-container
used to group elements h2
And p
which are created for each element of the array items
.
Usage
ngSwitch
you can use ng-container
to group elements that should be displayed depending on the value of the variable. For example:
<ng-container [ngSwitch]="status">
<div *ngSwitchCase="'success'">
<h2>Success!</h2>
<p>Your operation was successful.</p>
</div>
<div *ngSwitchCase="'error'">
<h2>Error!</h2>
<p>There was an error processing your request.</p>
</div>
<div *ngSwitchDefault>
<h2>Processing...</h2>
<p>Please wait while we process your request.</p>
</div>
</ng-container>
In this example ng-container
used to group elements div
which are displayed depending on the value of the variable status
.
Conclusion:
ng-container
is a useful structural directive that allows you to group elements without adding additional nodes to the DOM. You can use it to conditionally display elements, create elements using *ngFor
and grouping elements for use with ngSwitch
And *ngIf
.
In the next article I will tell you how ng-container is used in conjunction with ng-template and ngTemplateOutlet. Subscribe to follow!
These are the pies