How to use ng-show in Angular 2+?

Issue

ng-show is used in AngularJS (Angular 1) for conditionally displaying content. In Angular 2+ versions there are two ways you can conditionally display elements.

1st Solution – Using [hidden] attribute

You can use [hidden] attribute to conditionally show / hide HTML elements. Using [hidden] attribute will use CSS rules to show or Hide Elements. It will not remove elements from HTML

<img src="myImg.png" [hidden]="my-condition">

The above example will show the image when the condition “my-condition” is false. When the condition is true, the element will be hidden

If you need to show image when the condition is true, you can use

<img src="myImg.png" [hidden]="!my-condition">

2nd Solution – Using *ngIf attribute

You can use *ngIf attribute to conditionally show / hide HTML elements. Please note that *ngIf is not only hiding the element. It will remove the element from HTML, if the condition is false.

<img src="myImg.png" *ngIf="my-condition">

The above example will show the image when the condition “my-condition” is true.

Leave a Reply

(*) Required, Your email will not be published