【问题标题】:How to use TailwindCSS3 with ngClass?如何将 TailwindCSS3 与 ngClass 一起使用?
【发布时间】:2022-01-04 21:29:25
【问题描述】:

我正在尝试在 ngClass 的函数中使用 TailwindCSS。

在函数中生成了 TailwindCSS 类来维护我的模板,但它不起作用。

请检查我下面的代码

*.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}`;
  }
...

TailwindCSS3 不可能吗?

【问题讨论】:

    标签: angular tailwind-css ng-class


    【解决方案1】:

    似乎可以让它与 ngClass 和 Tailwindcss v3.0.13 和 Angular 13.1.3 一起使用

    这是我的解决方案:

    *.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;
        }
    }
    

    按钮的用法如下:

    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);
      }
    

    【讨论】:

    • 我有一个关于 TailwindCSS v3 的问题。这是因为 JIT 而发生的吗?
    • @honeybear 我不认为这是因为 JIT。我认为这可能是因为您可能错过了 ngClass 周围的方括号 []。我也不确定你是如何构建你的 CSS 文件的,所以我尽可能地为你提供了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 2020-10-23
    • 2021-01-02
    • 1970-01-01
    • 2023-03-13
    • 2014-09-25
    • 2016-01-30
    相关资源
    最近更新 更多