NgStyle

There are multiple ways to write the ngStyle expression.

1. Using the style attribute name and an expression that resolves to the value of the attribute.

<some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>

<p [ngStyle]="{'backgroundColor': darkTheme ? ‘#000’ : ‘#fff’ }"></p>
<p [ngStyle]="{'backgroundColor': theme === ‘dark’  ? ‘#000’ : ‘#fff’ }"></p>

2. Using an object expression which resolves to the whole style element.

...

primaryColor = ‘color: blue’;

3. Using an object expression which resolves to the style element value.

...

darkTheme = ‘#000’;

4. Bind the style directive along with the attribute

...

darkTheme = ‘#000’;

5. Assigning the value to the attribute using a CSS variable.

...
.my-element { 
	background-color: var(--my-background-color); 
}

.main-div { background-color: var(--my-background-color); }

Need Help With Angular Development?

Work with our skilled Angular developers to accelerate your project and boost its performance.

Hire Angular Developers

Support On Demand!

Related Q&A