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.
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.
Share Improve this question asked Apr 1, 2018 at 10:27 RajnishCoderRajnishCoder 3,7357 gold badges21 silver badges36 bronze badges2 Answers
Reset to default 5You 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>
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'
}