Angular 5 NgHide NgShow [hidden] Not Working


Answer :

If you want to just toggle visibility and still keep the input in DOM:

<input class="txt" type="password" [(ngModel)]="input_pw"   [style.visibility]="isHidden? 'hidden': 'visible'"> 

The other way around is as per answer by rrd, which is to use HTML hidden attribute. In an HTML element if hidden attribute is set to true browsers are supposed to hide the element from display, but the problem is that this behavior is overridden if the element has an explicit display style mentioned.

.hasDisplay {   display: block; }
<input class="hasDisplay" hidden value="shown" /> <input hidden value="not shown">

To overcome this you can opt to use an explicit css for [hidden] that overrides the display;

[hidden] {   display: none !important; } 

Yet another way is to have a is-hidden class and do:

<input [class.is-hidden]="isHidden"/>  .is-hidden {       display: none;  } 

If you use display: none the element will be skipped from the static flow and no space will be allocated for the element, if you use visibility: hidden it will be included in the flow and a space will be allocated but it will be blank space.

The important thing is to use one way across an application rather than mixing different ways thereby making the code less maintainable.

If you want to remove it from DOM

<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden"> 

Your [hidden] will work but you need to check the css:

<input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden" /> 

And the css:

[hidden] {   display: none !important; } 

That should work as you want.


2019 Update: I realize that this is somewhat bad advice. As the first comment states, this heavily depends on the situation, and it is not a bad practice to use the [hidden] attribute: see the comments for some of the cases where you need to use it and not *ngIf

Original answer:

You should always try to use *ngIf instead of [hidden].

 <input *ngIf="!isHidden" class="txt" type="password" [(ngModel)]="input_pw" > 

There are several blog posts about that topics, but the bottom line is, that Hidden usually means you do not want the browser to render the object - using angular you still waste resource on rendering it, and it will end up in the DOM anyway (and tricky users can see it with basic browser manipulation).


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable