Angular2:条件显示,绑定到[hidden]属性和* ngIf指令 [英] Angular2: conditional display, bind to [hidden] property vs. *ngIf directive

查看:939
本文介绍了Angular2:条件显示,绑定到[hidden]属性和* ngIf指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2中,假设我想有条件地显示< div> 块。


  1. < div [hidden] = isLoaded> Hello World!< / div> 其中 isLoaded 是对应 .ts 文件中的布尔值。

  2. 我知道即使< div> 没有在页面中显示,1.在DOM中仍然存在< div> ,而2.没有。还有其他的区别吗?他们每个人的优点和缺点是什么?

    解决方案

    区别在于 * ngIf 会从DOM中移除元素,而 [hidden] 通过设置 display:none code>。然而, [hidden] 的问题在于它可能被overiden,所以 div ,就像你的情况那样显示出来,你会抓住你的头为什么它不工作。



    总结一下, * ngIf [隐藏] 都不是 。前者从DOM中删除元素,而后者则切换 display CSS属性。


    In Angular2, let's say I want to conditionally display a <div> block. What's the difference between the following two ways.

    1. <div [hidden]=isLoaded>Hello World!</div> where isLoaded is a boolean in corresponding .ts file.

    2. <div *ngIf=isLoaded>Hello World!</div>

    I do know that even if the <div> is not shown in the page, 1. still has the <div> in the DOM while 2. doesn't. Are there any other differences? What're the pros and cons of each of them?

    解决方案

    The difference is that *ngIf will remove the element from the DOM, while [hidden] actually plays with the CSS style by setting display:none. However, the problem with [hidden] is that it can be overiden so the div, as in your case, would be displayed and you would be scratching your head why it doesn't work.

    To sum things up, *ngIf and [hidden] are not the same at all. The former removes an element from DOM, while the latter toggles display CSS property.

    这篇关于Angular2:条件显示,绑定到[hidden]属性和* ngIf指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆