Creating angular pipe using enum values

479 views Asked by At

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'
}

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

<div class="font-bold" [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;

}
4

There are 4 answers

1
Jovana On BEST ANSWER

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 class="font-bold" [ngClass]="{'activeClass': item.license==status.Active,
           'reviewClass': item.license==status.None}">
             {{item.license}}
</div>
1
MoxxiManagarm On

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

<div class="font-bold" [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 class="font-bold" appStatusColorDirective myStatus="Active">Active</div>
<div class="font-bold" appStatusColorDirective myStatus="None">None</div>
<div class="font-bold" appStatusColorDirective myStatus="Processing">
  Processing
</div>
<div class="font-bold" appStatusColorDirective myStatus="Expiring">
  Expiring
</div>

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

1
Eliseo On

A pipe it's only a class with a function "transform" that received a value and return "what-ever", but, Really it's not the best aproach to change a class or a color

E.g.

export class StatusPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    if (value == Status.Active) return 'activeClass';
    if (value == Status.None) return 'reviewClass';
    return null;
  }
}

See stackblitz

0
Muhammad Ahsan On

you can do it in a more simple fashion without the need for pipes.

https://stackblitz.com/edit/angular-ivy-saycxm?file=src/app/app.component.html