0

How to add dynamically css class using angular?

I want to get from backend style properties (i.e width, height) and create from this properties css style.

So, when in css I would have class="testClass", "testClass" should contains properties received from backend.

Is this possible?

1
  • I think you need to use <element style="width: {{widthFromDb }};" and add those properties there. Or add a <style> element in your component that transpile to a variable. something like <style>.myClass { width: {{widthFromDb }} }</style>CommentedFeb 16, 2018 at 14:32

1 Answer 1

2

Yes. You are looking for [ngClass], which works like this:

<some-element [ngClass]="'first second'">...</some-element> <some-element [ngClass]="['first', 'second']">...</some-element> <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element> <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element> <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element> 

Or you could also do:

<some-element [ngClass]="getClass()">...</some-element> getClass() { return this.http.get..... } 

and return a string. Or You could just assign a variable. It's very flexible to accommodate most situations. But you wouldn't "return properties". What you would do is return a class, which has those properties you want. To set specific properties, I'd recommend using Renderer2:

import { Renderer2 } from '@angular/core'; 

Which has the setStyle method:

this.renderer2.setStyle('your element', style: string (such as width), value: any (such as 32px)); 
2
  • But, for [ngClass] I have to have existing css class to assign, and I want to always set the same css class, but properties of class I get from backend. I.e. from backend I get string "{width: 500px; height: 34px;}" and from this, I want to create "testClass" and for some elements use class="testClass"
    – Karolke
    CommentedFeb 16, 2018 at 14:35
  • Then Renderer is the route you want to or use javascript/jquery.CommentedFeb 16, 2018 at 14:37

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.