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.
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.
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 .
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.
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.
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;
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With