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+?
ngShow and ngHide are two ng directives in AngularJS used to show and hide the elements respectively.
Definition and Usage The ng-hide directive hides the HTML element if the expression evaluates to true. ng-hide is also a predefined CSS class in AngularJS, and sets the element's display to none .
Basic Difference between ng-if, ng-show and ng-hideng-if can only render data whenever the condition is true. It doesn't have any rendered data until the condition is true. ng-show can show and hide the rendered data, that is, it always kept the rendered data and show or hide on the basis of that directives.
The main difference between angular ngIf directive & hidden or display:none is ngIf will add or remove the element from DOM based on condition or expression. hidden attribute in html5 and display none CSS will show or hide the HTML element.
The hidden
property can be used for that
[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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With