×
☰ See All Chapters

Angular ngStyle Directive

ngStyle directive allows to use the style option dynamically. When we compare the class and style attributes in regular HTML, class accepts the value of a css class declared separately and style attribute accepts the inline declarations of style options.

<html>

<head>

<style type="text/css">

.red {

        color: red;

        size: 20px;

}

</style>

</head>

<body>

        <p class="red">Hello</p>

        <p style="color: red; size: 20px;">Hi</p>

</body>

</html>

 

Same like class and style, we can compare ngClass and ngStyle.  Using ngStyle we can dynamically set styles of elements in the template.

Angular ngStyle Directive Example

app.component.ts

import { Component } from '@angular/core';

 

@Component({

        selector: 'app-tag',

        template: `<label [ngStyle]="{'color': fontColor, 'font-size': fontSize}">

                                www.java4coding.com

                  </label>

                                `

})

export class AppComponent {

        fontSize: string='20px';

        fontColor: string = 'red';

}

 

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

 

@NgModule({

  declarations: [

      AppComponent

  ],

  imports: [

    BrowserModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

index.html

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Angular Example</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

</head>

<body>

  <app-tag></app-tag>

</body>

</html>

Output

angular-ngstyle-directive-0
 

 

 


All Chapters
Author