Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable in style tag in angular template?

I am working on angular 5 application, and I have requirement of applying dynamic css in style tag in template. I have tried some solutions but they are not working.

app.component.ts

customCss : any;

constructor(){}

ngOnInit(){
   this.customCss['color'] = "red";
}

app.component.html

<div>
   <span class="custom_css">This is angular 5 application</span>
</div>

<style>
   .custom_css{
      color: {{customCss.color}};
   }
</style>

When I inspect the custom_css class in browser then in style it shows

.custom_css{
   color: {{customCss.color}};
}

Any help is appreciated.

like image 485
Lakhvir Singh Avatar asked Mar 23 '18 12:03

Lakhvir Singh


People also ask

How do you use variables in style?

The basics. To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.

How do I pass a template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

What is template input variable in Angular?

Angular assigns a template variable a value based on where you declare the variable: If you declare the variable on a component, the variable refers to the component instance. If you declare the variable on a standard HTML tag, the variable refers to the element.

Which keyword is used to set a variable in the template?

To create a variable template, define a yaml file with the keyword variables at the top and use key:value pairs to define the variables.


2 Answers

You can use [ngStyle] directive:

<span [ngStyle]="{'color': 'red'}">
 This is angular 5 application
</span>

Or like so:

<span [ngStyle]="applyStyles()">
 This is angular 5 application
</span>

And in component:

applyStyles() {
    const styles = {'color' : 'red'};
    return styles;
}
like image 59
Roberto Zvjerković Avatar answered Sep 23 '22 18:09

Roberto Zvjerković


By the way if you set the color like this:

<div [style.color]="color"></div>

where color='var(--cssValue)' it would not work!

However, this works correctly:

<div [ngStyle]="{color: color}"></div>
like image 43
Humberd Avatar answered Sep 25 '22 18:09

Humberd