角度|有条件地显示元素 [英] Angular | Display element conditionally

查看:62
本文介绍了角度|有条件地显示元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试有条件地显示元素.我应用于元素的这段代码应该可以工作:

I'm trying to display an element conditionally. This code that I applied to the element should work:

<a [style.display]="chatIsToggled ? 'display: block' : 'display: none'">
  link
</a>

问题在于,由于不安全的样式值",Angular不会应用样式.

The problem is that Angular doesn't apply the style because of "unsafe style value"

警告:清理不安全的样式值显示:无(请参见 http://g.co/ng/安全性#xss ).

实现我想要的工作的等效方法是什么?

What would be an equivalent way to achieve what I want to do?

推荐答案

不要重复显示 display ,只需传递值本身即可

Don't repeat the display, you only have to pass the value itself:

<a [style.display]="chatIsToggled ? 'block' : 'none'">
  link
</a>

如果您使用具有Display实用程序类的CSS框架(例如 Twitter Bootstrap ),您可以有条件地分配一个特殊的类:

If you use a CSS framework that has Display utility classes(like Twitter Bootstrap) you can conditionally assign a special class instead:

<a [class.d-block]="chatIsToggled">
  link
</a>

您也可以只使用* ngIf 结构指令:

You can also just use the *ngIf structural directive:

<a *ngIf="chatIsToggled">
  link
</a>

但这确实具有稍微不同的语义,因为如果不满足条件,它甚至不会呈现该元素.例如,这会影响其生命周期方法.

but that does have slightly different semantics since it won't even render the element if the condition isn't met. This impacts, for example, at which point its life cycle methods are called.

这篇关于角度|有条件地显示元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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