2

Is that possible to append CSS from a variable. for example

var myHtml = "<div>My example html</div>";

// in html i can do this

<div [innerHTML]="myHtml"></div> 

But what if I have CSS stored in variable. like below:-

var myCss = ".exampleClass {margin: 0;width: 100%;}";

How can I add this css variable in my CSS file OR in HTML as a working css?

I'm using Angular 4+ but even JavaScript solution also appreciated.

2 Answers 2

5

You can simply insert a new <style> tag into your page using JavaScript:

var myCss = ".exampleClass {margin: 0;width: 100%;color:blue}";

var style = document.createElement("STYLE");
style.innerText = myCss;
document.body.appendChild(style);
<div class="exampleClass">Lorem ipsum</div>

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

Comments

1

Try: <div [style.width.%]="WidthValue" [style.marginTop.px]="marginTopValue"></div>

where, in *.ts file, you are having value in a variable

WidthValue: number = 100;
marginTopValue: number = 0;

Adding one more way,

<div [ngStyle]="styleObject"></div>

where,

styleObject = {
  'width': '100px',
  'margin-top': '10px'
}

1 Comment

can't because i have lots of CSS and css can be changed dynamically form backend.

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.