Dynamic Styles

Hi Friends, This is Lakshman here.

As part of the Series "Angular Best Practices".

Today, We will go through Practices with Implement Dynamic Styles for Angular App.

Dynamic Styles

As Default, Every Component has its style.

In Some cases, we may require to switch between styles or classes.

For Example, we required to Display a Card, - Color Red for Error Status. - Color Green for Success Status.

ngStyle

What we usually do we will check for condition on ngStyle to change Color like below,

<div [ngStyle]="{'color': item.Status.toLocaleLowerCase() === 'error' ? 'red' : 'green'  }">

In ngStyle, we can't have multi-Condition in HTML. If we require, we need code like below,

In HTML:

<div [ngStyle]="{ 'color': getColor(item.Status) }">

In TS:

  //#region Switch Styles

  getColor(status: string) {
    switch (status.toLocaleLowerCase()) {
      case 'success':
        return 'green';
      case 'error':
        return 'red';
      case 'default':
        return 'gray';
    }
  }

  //#endregion

Each has its defects on it. By Using ngStyle,

  • May require Hard-Code of Styles in Code.
  • In Status Name Changed, it won't work.

It's better to use ngClass it has lots of benefits.

ngClass

Okay now using ngClass, we will be code like below,

In HTML:

<div [ngClass]="item.Status.toLocaleLowerCase()">

In SCSS:

.success {
    color: green;
}

.error {
    color: red;
}

.default {
    color: gray;
}

The Benefits are,

  • It doesn't require hard-code style in code.
  • We can change in SCSS File itself.
  • We may enhance the SCSS in respective to Browsers, Devices sizes.
  • Won't Override existing Classes applied via Styles to it.

On-road head, we will discuss a lot of things.

Looking forward to your comments and share your feedback.

Until that, I am Lakshman, Signing Off.

Comments

Popular posts from this blog

Model Mapper in Angular

Implement Logging in Angular with Firebase

Dockerize Angular App for Dev