Use Styles in Angular Component
To use inline styles in an Angular component, you can use the style
attribute of the component's template. The style
attribute allows you to apply CSS styles directly to an element in the template.
Here's an example of how you can use inline styles in an Angular component:
<div style="color: red; font-size: 20px;">Hello, world!</div>
This will apply the "color: red" and "font-size: 20px" styles to the div element.
You can also use Angular template expressions in the style
attribute to bind to component properties. For example:
<div [style.color]="color">Hello, world!</div>
This will bind the value of the color
property to the "color" style of the div element. You can update the value of the color
property in the component's class to change the color of the div element.
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent { public color = 'red'; }
You can also use the Angular ngStyle
directive to bind multiple styles to an element. The ngStyle
directive takes an object that maps style names to style values.
Here's an example of how you can use the ngStyle
directive:
<div [ngStyle]="{'color': color, 'font-size': fontSize}">Hello, world!</div>
This will bind the value of the color
property to the "color" style and the value of the fontSize
property to the "font-size" style of the div element.