11

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?

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
user2324232322
  • 303
  • 2
  • 6
  • 16
  • 4
    The property is named `style.display`. So you don't need to repeat `display` in the value. `[style.display]="chatIsToggled ? 'block' : 'none'"`. But why not just use *ngIf? – JB Nizet Nov 10 '17 at 21:27
  • Does this answer your question? [Angular 2 Show and Hide an element](https://stackoverflow.com/questions/35163009/angular-2-show-and-hide-an-element) – Liam Feb 10 '20 at 11:39

1 Answers1

24

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.

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
  • And yes, like you said I am not trying to use ngIf since that would result in a new call to my server every time the user toggles the chat window – user2324232322 Nov 10 '17 at 21:35
  • 1
    If that caused backend calls you should probably change the design of your code as that can definitely be avoided. :-) Please also mark the answer as accepted if it solved your problem. – Ingo Bürk Nov 10 '17 at 21:37
  • Yes, I am just waiting for stack letting me accept the answer. :) – user2324232322 Nov 10 '17 at 21:40
  • I am just using the ngOnInit hook to request the messages once the chat component loads. Since the chat component is always loaded this only results to one call during the entire visit, I thought this is a good design pattern? Please correct me if I'm wrong – user2324232322 Nov 10 '17 at 21:42
  • It's not always a good idea to directly make http calls in components. You could abstract that into an injectable service with the appropriate scope. It only loads the data when asked to, but can then cache it. – Ingo Bürk Nov 11 '17 at 07:31
  • I'm using a service, but the caching thing is new to me. I'll look into that – user2324232322 Nov 11 '17 at 08:47