16

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?

2
  • 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? Commented Nov 10, 2017 at 21:27
  • Does this answer your question? Angular 2 Show and Hide an element Commented Feb 10, 2020 at 11:39

1 Answer 1

30

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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
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.
Yes, I am just waiting for stack letting me accept the answer. :)
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
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.