Karolke
Karolke

Reputation: 103

Angular add css style dynamically

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?

Upvotes: 0

Views: 166

Answers (1)

David Anthony Acosta
David Anthony Acosta

Reputation: 4918

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));

Upvotes: 2

Related Questions