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

Mihai Răducanu picture Mihai Răducanu · Feb 23, 2016 · Viewed 628k times · Source

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+?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Feb 23, 2016

Just bind to the hidden property

[hidden]="!myVar"

See also

issues

hidden has some issues though because it can conflict with CSS for the display property.

See how some in Plunker example doesn't get hidden because it has a style

:host {display: block;}

set. (This might behave differently in other browsers - I tested with Chrome 50)

workaround

You can fix it by adding

[hidden] { display: none !important;}

To a global style in index.html.

another pitfall

hidden="false"
hidden="{{false}}"
hidden="{{isHidden}}" // isHidden = false;

are the same as

hidden="true"

and will not show the element.

hidden="false" will assign the string "false" which is considered truthy.
Only the value false or removing the attribute will actually make the element visible.

Using {{}} also converts the expression to a string and won't work as expected.

Only binding with [] will work as expected because this false is assigned as false instead of "false".

*ngIf vs [hidden]

*ngIf effectively removes its content from the DOM while [hidden] modifies the display property and only instructs the browser to not show the content but the DOM still contains it.