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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…