ngShow and
ngHide are two ng directives in AngularJS used to show and hide the elements respectively. ngShow is used to show a div tab by linking it to a Boolean variable in the script. If the value of the variable is true then the item is displayed, else the item remains hidden and the vice versa happens in the case of ngHide.
Example for ng-show: This example demonstrates how ngShow works.
Output:
👁 Image
Similarly, if ng-show value set to false then it will disappear.
Example for ng-hide: This example demonstrates how nghide works.
Output: Output here is a black screen because the ng-hide is set to true, that means the GeeksForGeeks is hidden. Similarly if true is changed to false then it appears as follows:
👁 Image
Implementation on Angular 2+
In angular, there are two ways to implement ng-hide and ng-show:
- By using
[hidden]
property:[hidden]
property in angular, modifies the display property and does no change with the DOM. It only instructs the browser to not show the content
Syntax:
<div [hidden]="boolean_var"></div>
As it don't do any hindrance with the DOM thus, if display property is used in CSS then this will fail. For example for the upper example, the [hidden] will fail if done as follows.
<div [hidden]="boolean_var" style="display:block; ></div>
The RHS side of hidden property consists of the name of the boolean variable which is in the component class. The value of that variable decides whether [hidden]
will hide or not.
Example:
- The Template file
- The Component Class
- Output: This don't show anything on the screen.
- By using
*ngIf
directive: It is a more effective way that [hidden]. It effectively removes the content from the DOM and thus there are loopholes in this method.
Syntax:
<div *ngIf="boolean_var"></div>
Similar to [hidden] property the RHS side of this property consists of the name of the boolean variable which is in the component class. The value of that variable decides whether the content will be in the DOM or not.
Example:
- The Template file
- The Component Class:
- Output:
This will be Shown..