The Built-in `NgStyle` Directive
Let’s learn about `NgStyle`, a built-in attribute directive.
We'll cover the following
In the previous lesson, we learned how to change the styling of elements using dynamically applied CSS classes. But, is that all we need in the case of dynamic styling?
Let’s think about specific situations when we need to apply precise styling, like a calculated color or a particular size. We are working with values that are calculated at runtime and can’t be predicted. So, we can’t prepare CSS classes with the required styling beforehand.
However, we need to be careful with this directive. Styles applied using NgStyle
are set directly, like inline styles, so they take precedence over other CSS rules. The only way to override them is to use the !important
keyword, which is not considered to be a good practice since it can cause problems in CSS later.
The NgStyle
syntax
The syntax of the NgStyle
directive is very straightforward and easy to remember:
<p [ngStyle]="{fontWeight: 'bold'}">
Hello there
</p>
We need to assign an object with the following:
- Keys are CSS properties written in camelCase.
- Values are the values for the corresponding CSS properties.
At runtime, the above code will produce these HTML results in the browser:
<p style="font-weight: bold">
Hello there
</p>
Let’s discuss how to make the results more dynamic. For now, we’ve only seen a static use of NgStyle
which doesn’t have the ability to change the styling in real time. We can change that by using the component’s properties to populate NgStyle
.
@Component({
selector: 'app-text',
template: `<p [ngStyle]="{'fontWeight': fontWeightStyle }">Hello there</p>`,
})
export class TextComponent {
@Input() isBold: boolean = false;
get fontWeightStyle(): string {
if(this.isBold) {
return 'bold';
} else {
return 'normal';
}
}
}
In this example, we provide dynamic styling of the CSS property font-weight
using a getter
function that resolves style based on the input property.
So, if property equals true, the getter
function returns bold
. In the other case, it returns normal
. This value is used to populate styling through NgStyle
.
Below, we’ll find a working example:
Get hands-on with 1400+ tech skills courses.