Reputation: 109
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?
Upvotes: 4
Views: 5549
Reputation: 141
Adding an answer here because this is the top result when looking this up. Tailwind now supports ngClass. Below is a quick example of a p tag that is invisible if there are no errors, and visible with red text if there are.
<p
[ngClass]="{
'visible text-red-600': fieldError(usernameContName, authForm, 'required'),
invisible: !fieldError(pwContName, authForm, 'required')
}">
Username required.
</p>
Upvotes: 7
Reputation: 192
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);
}
Upvotes: 2