javascript - How to append CSS from a variable in CSS or HTML file? Angular 4+ - Stack Overflow

Is that possible to append CSS from a variable. for examplevar myHtml = "<div>My example htm

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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>

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744719134a4589803.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信