How to use TailwindCSS3 with ngClass?

I'm trying to use TailwindCSS in function inside ngClass.

TailwindCSS classes were generated in function to maintain my template but it doesn't work.

Please check my code below

*.component.html

...
<div class="grid grid-cols-12">
  <div ngClass="generateCol(fieldUI)">
...

*.component.ts

...
  generateCol(fieldUI: any) {
    return `col-span-12 sm:col-start-${fieldUI.startCol} sm:col-end-${fieldUI.endCol}`;
  }
...

Is it impossible with TailwindCSS3?


Solution 1:

It seems it is possible to get it to work with ngClass and Tailwindcss v3.0.13 and Angular 13.1.3

This is my solution below:

*.component.html

<button [ngClass]="getValidateStyle()" 
  type="button" 
  (click)="buttonClicked($event)">
    <span class="px-2">{{text}}</span>
</button>

*.component.ts

  @Output() onClick = new EventEmitter<any>();
  @Input() text: string|any;
  availableStyles: string[] = ['primary', 'secondary'];
  @Input() styleName!: string | "primary";

  constructor() { }

  ngOnInit(): void {
  }

  getValidateStyle(){
   if(this.availableStyles.includes(this.styleName))
   {
     return this.styleName;
   }   
   return "primary";
  }

  buttonClicked(event: any) {
    this.onClick.emit(event);
  }

*.component.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components{

    .primary{

        @apply px-2 flex rounded items-center text-sm bg-sky-100;
    }
}

@layer components{

    .secondary{

        @apply px-2 flex rounded items-center text-sm bg-sky-500;
    }
}

The usage of the button looks like this:

somefile.component.html

  <app-custom-button 
    styleName="secondary"
    text="This is a second button"
    (onClick)="logToConsole($event)">
  </app-custom-button>

somefile.component.ts

  logToConsole(event: any): void{
    console.log("Button clicked", event);
  }