Angular 2+ 中 ngShow 和 ngHide 的等价物是什么? [英] 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.
在 AngularJS 中我会写
In AngularJS I would write
<div ng-show="myVar">stuff</div>
如何在 Angular 2+ 中执行此操作?
How can I do this in Angular 2+?
推荐答案
hidden
属性可用于
[hidden]="!myVar"
另见
问题
hidden
有一些问题,因为它可能与 display
属性的 CSS 冲突.
hidden
has some issues though because it can conflict with CSS for the display
property.
在 Plunker 示例中查看如何some
不会被隐藏,因为它有一个样式
See how some
in Plunker example doesn't get hidden because it has a style
:host {display: block;}
设置.(这在其他浏览器中可能会有所不同 - 我使用 Chrome 50 进行了测试)
set. (This might behave differently in other browsers - I tested with Chrome 50)
解决方法
您可以通过添加来修复它
You can fix it by adding
[hidden] { display: none !important;}
到 index.html
中的全局样式.
另一个陷阱
hidden="false"
hidden="{{false}}"
hidden="{{isHidden}}" // isHidden = false;
与
hidden="true"
并且不会显示元素.
hidden="false"
将分配字符串 "false"
被认为是真实的.
只有值 false
或删除属性才会真正使元素可见.
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.
只有与 []
绑定才能按预期工作,因为此 false
被分配为 false
而不是 false"代码>.
Only binding with []
will work as expected because this false
is assigned as false
instead of "false"
.
*ngIf
vs [hidden]
*ngIf
vs [hidden]
*ngIf
有效地从 DOM 中删除其内容,而 [hidden]
修改了 display
属性并且只指示浏览器不显示内容,但 DOM 仍然包含它.
*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.
这篇关于Angular 2+ 中 ngShow 和 ngHide 的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!