In Angular, ngStyle
is a built-in directive that allows you to set inline styles dynamically based on the values of component properties.
Here's an example of how to use ngStyle
in an Angular component template:
html<div [ngStyle]="{ 'color': textColor, 'font-size': fontSize + 'px' }">
This text will be styled dynamically based on component properties.
</div>
In this example, ngStyle
is applied to a div
element. The value of ngStyle
is an object that contains one or more style properties and their values. In this case, the color
property is set to the value of the textColor
property of the component, and the font-size
property is set to the value of the fontSize
property, with the px
unit appended to it.
To use this ngStyle
directive, you need to define the textColor
and fontSize
properties in your component class:
typescriptimport { Component } from '@angular/core';
@Component(
{
selector: 'app-example',
templateUrl: './example.component.html',
}
)
export class ExampleComponent
{
textColor = 'red';
fontSize = 20;
}
In this example, the ExampleComponent
class defines textColor
and fontSize
properties with initial values. These properties can be changed dynamically at runtime, and the ngStyle
directive will update the inline styles of the div
element accordingly.
Comments
Post a Comment