【问题标题】:Angular Button Color Change with Condition角度按钮颜色随条件变化
【发布时间】:2021-05-06 06:49:39
【问题描述】:

在我的代码中,我有一个单元格列表,我以按钮的形式显示该列表。在这些按钮上,您可以看到单元格内的元素数量。如果一个单元格是空的,我希望它的按钮是绿色的,如果它有任何元素,我希望它是红色的。我的代码如下,我该怎么做?

 <button mat-button class="green fuse-white-fg" 
                            *ngFor="let prm of cell">Package Count: {{prm.PackageCount}}</button>

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    另一种方法。

    <button mat-button [class.green]="!prm.PackageCount" [class.red]="prm.PackageCount" *ngFor="let prm of cell">
      Package Count: {{prm.PackageCount}}
    </button>
    

    【讨论】:

      【解决方案2】:

      你可以使用ngStyle属性:

      <button mat-button [ngStyle]="{ 'background-color': prm.PackageCount ? 'green' : 'red' }" *ngFor="let prm of cell">
        Package Count: {{prm.PackageCount}}
      </button>
      

      【讨论】:

        【解决方案3】:

        您可以使用ngclass

         <button mat-button class="fuse-white-fg" 
                            [ngClass] = "{'green':!prm.PackageCount, 'red':prm.PackageCount>0}"
                            *ngFor="let prm of cell">Package Count: {{prm.PackageCount}}</button>
        

        greenred 是 css 类

        【讨论】:

        • 感谢按钮变红了。但是,空的(绿色的)从屏幕上消失了。我应该添加其他内容吗?
        • 你的绿色玻璃是如何定义的?
        • 你能告诉我它们是从 DOM 中消失还是只是一种你看不到的颜色?
        • 只是颜色,它们并没有从 DOM 中消失
        • 好的,我重新阅读了您的问题并相应地更新了我的答案 - 如果什么都没有,您希望它是绿色的,但这并不一定意味着计数为 0
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 2019-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多