[angular] What is the equivalent of ngShow and ngHide in Angular 2+?

I have a number of elements that I want to be visible under certain conditions.

In AngularJS I would write

<div ng-show="myVar">stuff</div>

How can I do this in Angular 2+?

This question is related to angular angular-components angular-template

The answer is


My issue was displaying/hiding a mat-table on a button click using <ng-container *ngIf="myVar">. The 'loading' of the table was very slow with 300 records at 2-3 seconds.

The data is loaded using a subscribe in ngOnInit(), and is available and ready to be used in the template, however the 'loading' of the table in the template became increasingly slower with the increase in number of rows.

My solution was to replace the *ngIf with:

_x000D_
_x000D_
<div [style.display]="activeSelected ? 'block' : 'none'">
_x000D_
_x000D_
_x000D_

. Now the table loads instantly when the button is clicked.


To hide and show div on button click in angular 6.

Html Code

<button (click)=" isShow=!isShow">FormatCell</button>
<div class="ruleOptionsPanel" *ngIf=" isShow">
<table>
<tr>
<td>Name</td>
<td>Ram</td>
</tr>
</table>
</div>

Component .ts Code

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
 isShow=false;
  }

this works for me and it is way to replace ng-hide and ng-show in angular6.

enjoy...

Thanks


If your case is that the style is display none you can also use the ngStyle directive and modify the display directly, I did that for a bootstrap DropDown the UL on it is set to display none.

So I created a click event for "manually" toggling the UL to display

<div class="dropdown">
    <button class="btn btn-default" (click)="manualtoggle()"  id="dropdownMenu1" >
    Seleccione una UbicaciĆ³n
    <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" [ngStyle]="{display:displayddl}">
        <li *ngFor="let object of Array" (click)="selectLocation(location)">{{object.Value}}</li>                                
     </ul>
 </div>    

Then on the component I have showDropDown:bool attribute that I toggle every time, and based on int, set the displayDDL for the style as follows

showDropDown:boolean;
displayddl:string;
manualtoggle(){
    this.showDropDown = !this.showDropDown;
    this.displayddl = this.showDropDown ? "inline" : "none";
}

I find myself in the same situation with the difference than in my case the element was a flex container.If is not your case an easy work around could be

[style.display]="!isLoading ? 'block' : 'none'"

in my case due to the fact that a lot of browsers that we support still need the vendor prefix to avoid problems i went for another easy solution

[class.is-loading]="isLoading"

where then the CSS is simple as

&.is-loading { display: none } 

to leave then the displayed state handled by the default class.


Use hidden like you bind any model with control and specify css for it:

HTML:

<input type="button" class="view form-control" value="View" [hidden]="true" />

CSS:

[hidden] {
   display: none;
}

Use the [hidden] attribute:

[hidden]="!myVar"

Or you can use *ngIf

*ngIf="myVar"

These are two ways to show/hide an element. The only difference is: *ngIf will remove the element from DOM while [hidden] will tell the browser to show/hide an element using CSS display property by keeping the element in DOM.


Best way to deal with this issue using ngIf Because this well prevent getting that element render in front-end,

If you use [hidden]="true" or style hide [style.display] it will only hide element in front end and someone can change the value and visible it easily, In my opinion best way to hide element is ngIf

<div *ngIf="myVar">stuff</div>

and also If you have multiple element (need to implement else also) you can Use <ng-template> option

<ng-container *ngIf="myVar; then loadAdmin else loadMenu"></ng-container>
<ng-template #loadMenu>
     <div>loadMenu</div>
</ng-template>

<ng-template #loadAdmin>
     <div>loadAdmin</div>
</ng-template>  

sample ng-template code


for me, [hidden]=!var has never worked.

So, <div *ngIf="expression" style="display:none;">

And, <div *ngIf="expression"> Always give correct results.


For anybody else stumbling across this issue, this is how I accomplished it.

import {Directive, ElementRef, Input, OnChanges, Renderer2} from "@angular/core";

@Directive({
  selector: '[hide]'
})
export class HideDirective implements OnChanges {
  @Input() hide: boolean;

  constructor(private renderer: Renderer2, private elRef: ElementRef) {}

  ngOnChanges() {
    if (this.hide) {
      this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'hidden');
    } else {
      this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'visible');
    }
  }
}

I used 'visibility' because I wanted to preserve the space occupied by the element. If you did not wish to do so, you could just use 'display' and set it to 'none';

You can bind it to your html element, dynamically or not.

<span hide="true"></span>

or

<span [hide]="anyBooleanExpression"></span>

<div [hidden]="myExpression">

myExpression may be set to true or false


If you are using Bootstrap is as simple as this:

<div [class.hidden]="myBooleanValue"></div>

According to Angular 1 documentation of ngShow and ngHide, both of these directive adds the css style display: none !important;, to the element according to the condition of that directive (for ngShow adds the css on false value, and for ngHide adds the css for true value).

We can achieve this behavior using Angular 2 directive ngClass:

/* style.css */
.hide 
{
    display: none !important;
}

<!-- old angular1 ngShow -->
<div ng-show="ngShowVal"> I'm Angular1 ngShow... </div>

<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': !ngShowVal }"> I'm Angular2 ngShow... </div>

<!-- old angular2 ngHide -->
<div ng-hide="ngHideVal"> I'm Angular1 ngHide... </div>

<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': ngHideVal }"> I'm Angular2 ngHide... </div>

Notice that for show behavior in Angular2 we need to add ! (not) before the ngShowVal, and for hide behavior in Angular2 we don't need to add ! (not) before the ngHideVal.


Sorry, I have to disagree with binding to hidden which is considered to be unsafe when using Angular 2. This is because the hidden style could be overwritten easily for example using

display: flex;

The recommended approach is to use *ngIf which is safer. For more details, please refer to the official Angular blog. 5 Rookie Mistakes to Avoid with Angular 2

<div *ngIf="showGreeting">
   Hello, there!
</div>

If you just want to use the symmetrical hidden/shown directives that AngularJS came with, I suggest writing an attribute directive to simplify the templates like so (tested with Angular 7):


import { Directive, Input, HostBinding } from '@angular/core';

@Directive({ selector: '[shown]' })
export class ShownDirective {
  @Input() public shown: boolean;

  @HostBinding('attr.hidden')
  public get attrHidden(): string | null {
    return this.shown ? null : 'hidden';
  }
}

Many of the other solutions are correct. You should use *ngIf where ever possible. Using the hidden attribute can have unexpected styles applied, but unless you are writing components for others, you probably know if it is. So for this shown directive to work, you will also want to make sure that you add:

[hidden]: {
  display: none !important;
}

to your global styles somewhere.

With these you can use the directive like so:

<div [shown]="myVar">stuff</div>

with the symmetrical (and opposite) version like so:

<div [hidden]="myVar">stuff</div>

To add on to the shoulds - yous should also us a prefix like so [acmeShown] vs just [shown].

The main reason I used a shown attribute directive is for converting AngularJS code to Angular -AND- when the content that is being hidden contains container components that cause XHR round trips. The reason I don't just use [hidden]="!myVar" is that often enough it is more complicated like: [hidden]="!(myVar || yourVar) && anotherVar" - yes I can invert that, but it is more error prone.[shown]` is simply easier to think about.


in bootstrap 4.0 the class "d-none" = "display: none!important;"

<div [ngClass]="{'d-none': exp}"> </div>

There are two examples on Angular documents https://angular.io/guide/structural-directives#why-remove-rather-than-hide

A directive could hide the unwanted paragraph instead by setting its display style to none.

<p [style.display]="'block'">
  Expression sets display to "block".
  This paragraph is visible.
</p>

<p [style.display]="'none'">
  Expression sets display to "none".
  This paragraph is hidden but still in the DOM.
</p>

You can use [style.display]="'block'" to replace ngShow and [style.display]="'none'" to replace ngHide.


<div [hidden]="flagValue">
---content---
</div>

this is what worked for me:

<div [style.visibility]="showThis ? 'visible' : 'hidden'">blah</div>

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular-components

How to rename a component in Angular CLI? How to Update a Component without refreshing full page - Angular Angular 2 'component' is not a known element How to get element's width/height within directives and component? Call child component method from parent class - Angular How to style child components from parent component's CSS file? What is the equivalent of ngShow and ngHide in Angular 2+? Angular 2: How to style host element of the component? How can I select an element in a component template?

Examples related to angular-template

How and where to use ::ng-deep? How to use *ngIf else? Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays Dynamic tabs with user-click chosen components Getting reference to child component in parent component How to use Angular2 templates with *ngFor to create a table out of nested arrays? What is the equivalent of ngShow and ngHide in Angular 2+? Angular: conditional class with *ngClass