1
votes

enter image description here

I have Issue to create Dynamic css class in component HTML file... Right now I am using inline css like this

<div class="" [style.color]="mapData.theme.bodyFontColor"></div>

using angular functionalty.. but i need a class where I should change attribute dynamically. Example

.wrapper{
 color : mapData.theme.bodyFontColor;
 font-family: mapData.theme.bodyFontFamily;
}

if you seen screenshot there is a option to change color of template so just I need to update that color instantly in my class attribute..

is it possible?

2
You can't assign a ts value to a css/scss definition, but you can use [ngStyle] to dinamically change the css value binded to a variable defined in the ts code. IE: <div class="wrapper" [ngStyle]="{'color' : mapData.theme.bodyFontColor}"></div> - Jacopo Sciampi

2 Answers

0
votes

Workaround: you can do it by using global css-class. E.g. in Angular-CLI we can define global classes in ./src/styles.scss and there you can define your class with default values e.g.

.wrapper {
 color : black;
}

And then inside you component .ts you can dynamically modify this class using direct access to document styles as follows (for standard angular-CLI styles.scss is at index 2 - .styleSheets[2] but it can change in different versions/projects - it also depends of previously defined additional styles in index.html file)

let wrapperClass = [...(<any>document.styleSheets[2]).cssRules]
                    .find(x=> x.selectorText=='.wrapper');

wrapperClass.style.color = mapData.theme.bodyFontColor;
wrapperClass.style['font-family'] = mapData.theme.bodyFontFamily

In this way you can also access to pseudo elements e.g. .wrapper:hover. You can use this approach (direct access to document styles) to load (e.g. from database) dynamic skin for whole frontend (in that case you should not use local-styles for your components but only global in ./src/style.scss)

-2
votes

Yes this is possible,

<div [className]="'class' + someValue"></div

you can use class attribute for this. Check here for more info.