Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular | Display element conditionally

Tags:

angular

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>

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

WARNING: sanitizing unsafe style value display: none (see http://g.co/ng/security#xss).

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

like image 557
user2324232322 Avatar asked Nov 10 '17 21:11

user2324232322


1 Answers

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

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

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>

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.

like image 157
Ingo Bürk Avatar answered Sep 18 '22 08:09

Ingo Bürk