Using tailwind in Angular library

Discussão em 'Angular' iniciado por justAnotherDev, Janeiro 24, 2025.

  1. I'm setting up a new Angular library that integrates with Tailwind CSS, and I have a button component that looks like this:

    <button [ngClass]="[passedClass]">Button Text</button>


    In the associated .scss file, I'm applying some default Tailwind styles using the @apply directive:

    button {
    @apply px-3 py-2 bg-primary text-primary-text;
    }


    I want to allow users of the component to pass custom Tailwind classes (e.g., bg-indigo-500) via the passedClass variable, so they can override the default styles. However, when I do this, the utility classes don’t override my @apply styles because they have a lower priority in the CSS cascade.

    I can get it to work by setting ViewEncapsulation.None on the component, but I'm not sure if this is the best or most maintainable approach. Is there a better way to ensure that dynamically passed Tailwind classes can properly override the styles applied using @apply?

    What is the recommended way to achieve the desired behavior where dynamic tailwind utility classes passed via ngClass can override styles applied using Tailwind's @apply directive in an Angular component?

    Are there better alternatives to using ViewEncapsulation.None for this case?

    Thanks in advance!

    Continue reading...

Compartilhe esta Página