ngStyle

ngStyle directive is used to add inline css in angular. [ngStyle] can use key-value pair for css properties and values or use collection of css properties in component.

For single css, use key-value pair in [ngStyle].

For multiple css properties, use object name in [ngStyle].

Also don't forget to include CommonModule in app.component.ts to use ngStyle directive.

ngStyle Example

This is ngStyle Example

        <!-- app.component.html -->

<p [ngStyle]="{'color':'#00f'}">This is ngStyle Example</p>
        <!-- app.component.ts -->
  import { Component } from '@angular/core';
  import { RouterOutlet } from '@angular/router';
  import { CommonModule } from '@angular/common';
  
  @Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, CommonModule],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
  })
  export class AppComponent {
    title = 'demo';
  }

ngStyle with multiple properties

This is ngStyle Example

        <!-- app.component.html -->
    
<p [ngStyle]="{'color':'#00f','text-align':'center'}">This is ngStyle Example</p>

ngStyle with object

ngStyle can also get value form object in component. This is recommended when we have multiple properties.

We can store one or more properties in class component and then reuse in template directive.

ngStyle Example

        <!-- app.component.ts -->

export class AppComponent {
    css={
        color:'#fff',
        background:'#222',
        padding:'.5rem',
        border:'1px solid #666'
    };
}    
        <!-- app.component.html -->

<p [ngStyle]="css">ngStyle Example</p>