In Angular, we have attribute directives like ngClass and ngStyle with the help of these directives, you can dynamically add CSS and classes. it is useful for creating dynamic and responsive user interfaces. Let’s explore how can we use each of these directives

Using ngClass

The ngClass the directive allows you to conditionally apply CSS classes to an HTML element based on the logic in your component. You can easily toggle the styles based on user interactions or any other dynamic conditions.

Here’s how you can use ngClass

Goto your component TypeScript .ts file, define the properties of the classes to be applied

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

@Component({
  selector: 'app-header',
  templateUrl: `header.component.html`,
  styles: [
    '.active { background-color: green; }'
  ]
})
export class NgClassExampleComponent {
  isActivated: boolean = true;
}
header.component.ts – TypeScript

Goto your HTML file, and add ngClass Directive on your HTML element, it will apply classes based on the values of the properties defined in the component.

    <div [ngClass]="{'active': isActivated, 'italic': isActivated}">Dynamic Styling</div>
HTML

Using ngStyle

With Help of ngStyle directive you can apply inline styles to an HTML element based on your component. This can be helpful for conditionally toggle element styles based on various conditions.

Here’s how you can use ngStyle

Goto your component TypeScript .ts file, define the properties of the styles to be applied

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

@Component({
  selector: 'app-header',
  template: 'header.component.html'
})
export class NgStyleExampleComponent {
  fontSize: number = 20;
  isUserLoggedIn = true;
  textColor: string = 'blue';
}
header.component.ts – TypeScript

Goto your HTML file, and add ngStyle Directive on your HTML element, it will apply styles based on the values of the properties defined in the component.

<div [ngStyle]="{'font-size.px': isUserLoggedIn ? fontSize : null, 'color': textColor}">Dynamic Styling</div>
HTML
Remember that ngClass and ngStyle allow you to apply styles conditionally on your html DOM based on data in your component.

Happy Coding ☺️

Comments to: How to NgClass and NgStyle in Angular | Angular Tutorial – 7

    Your email address will not be published. Required fields are marked *

    Attach images - Only PNG, JPG, JPEG and GIF are supported.