Home > Mobile >  Creating angular pipe using enum values
Creating angular pipe using enum values

Time:10-20

i want to create a pipe using enum values to show me text colors depending on the status . this is my enum class :

export  enum Status {
  Active = 'Active',
  None = 'None',
  Processing = 'Processing',
  Expiring ='Expiring'
}

And i was doing this using ngClass ,depending on the status the color of text changes ,this what i have done :

<div  [ngClass]="{activeClass: item.license=='Active',
           reviewClass: item.license=='None'}">
             {{item.license}}</div></div>

active and review are two css classes :

.activeClass {
 color: #32CD32;
 
}

.reviewClass {
 color: #CD7F32;

}

CodePudding user response:

In order to use enums in template, you need to declare it in .ts file. The solution for you problem would be:

component.ts

status = Status;

Also you need to modify template like so:

component.html

<div  [ngClass]="{'activeClass': item.license==status.Active,
           'reviewClass': item.license==status.None}">
             {{item.license}}
</div>

CodePudding user response:

A pipe is not a solution for that. With a pipe you could only shorten the ngClass assignment like this:

<div  [ngClass]="item.license | getClassName">

What you need instead is a directive you can reuse. For example:

import { Directive, HostBinding, Input } from '@angular/core';

export enum Status {
  Active = 'Active',
  None = 'None',
  Processing = 'Processing',
  Expiring = 'Expiring',
}

const STATUS_COLOR_MAP: Record<Status, string> = {
  [Status.Active]: '#32CD32',
  [Status.None]: '#CD7F32',
  [Status.Processing]: '#0000ff',
  [Status.Expiring]: '#ff0000',
};

@Directive({
  selector: '[appStatusColorDirective]',
})
export class StatusColorDirective {
  @HostBinding('style.color')
  color: string;

  @Input()
  set myStatus(key: Status) {
    this.color = STATUS_COLOR_MAP[key];
  }
}

With example template

<div  appStatusColorDirective myStatus="Active">Active</div>
<div  appStatusColorDirective myStatus="None">None</div>
<div  appStatusColorDirective myStatus="Processing">
  Processing
</div>
<div  appStatusColorDirective myStatus="Expiring">
  Expiring
</div>

Try it here: https://stackblitz.com/edit/angular-r6jac8?file=src/app/app.component.ts

  • Related