RajnishCoder
RajnishCoder

Reputation: 3735

How to append CSS from a variable in CSS or HTML file? Angular 4+

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.

Upvotes: 2

Views: 5668

Answers (2)

Sebastian Speitel
Sebastian Speitel

Reputation: 7346

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>

Upvotes: 5

Srikanth Sharma
Srikanth Sharma

Reputation: 2067

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'
}

Upvotes: 1

Related Questions