BlackHoleGalaxy
BlackHoleGalaxy

Reputation: 9662

Angular 2 add class and style to existing one from a JSON

In our component, we retrieve through http a JSON containing various styling for our element:

{
  id: 1,
  style: "color: red; background-color: white;",
  class: "fa-times",
},
{
  id: 2,
  style: "",
  class: "fa-check active",
}

I can't really change the JSON retrieves as it's from an external source.

Then I want to apply that style in a ngFor loop:

<li *ngFor="let element of elements">
  <i class="fa" style=""></i> {{element .id}}
</li>

But now I want to add the classes and styles defined as strings in JSON into my element.

Classes

I tried something like [class] = "fa {{element.class}}" but it triggers an error:

Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 3 in [fa {{element.class}}]

I managed to get the class part of my request working by using ngClass as suggered in some website and an answer here:

class="fa" [ngClass]="possibility.class"

It works. But I still struggle to apply requested styles.

Styles

I tried several methods:

[style]="possibility.style"

It then triggers the xss protection of Angular2:

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

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

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

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

I also tried style="{{possibility.style}}" and of course it triggers the same XSS protection guard.

I tried the ngStyle method:

[ngStyle]="possibility.style"

But it seems not to be able to parse the style as it is parsed from JSON (e.g: string color: green; background-color: white;. Even a single style like color: green; breaks the script):

Error in ./ProjectComponent class ProjectComponent - inline template:15:14 caused by: Cannot find a differ supporting object 'color: green'

ORIGINAL EXCEPTION: Cannot find a differ supporting object 'color: green'

Upvotes: 2

Views: 2661

Answers (2)

muetzerich
muetzerich

Reputation: 5720

You can use ngClass:

<li *ngFor="let element of elements">
  <i class="fa" [ngClass]="element.class"></i> {{element.id}}
</li>

Upvotes: 3

DOMZE
DOMZE

Reputation: 1369

Have the class attribute bind to a property of your component:

<i [class]="myProperyInMyComponent"></i> {{element .id}}

in your component:

myPropertyInMyComponent: string

once you get back the result from your http:

this.myPropertyInMyComponent = ....

see template syntax

Upvotes: 1

Related Questions