【问题标题】:Conditional button color attr in Angular Material (Components)Angular Material(组件)中的条件按钮颜色属性
【发布时间】:2020-01-17 16:55:14
【问题描述】:

我有一个接受输入的组件..@Input() coDeliveryCandidates: DeliverySlotView[];

这是在模板中使用的:

<ng-container *ngFor="let coDeliverySlotView of (coDeliveryCandidates | async)">
  <button
    mat-raised-button
    [color]=""
  >
    {{ label  }}
  </button>
</ng-container>

color 属性将字符串作为值,我想做类似的事情:

[color]="{
  black: coDeliverySlotView.slotId === bookedSlot.slotId,
  grey: !coDeliverySlotView.slotId === bookedSlot.slotId
}"

这里我使用与 ngClass 相同的语法,但我猜它不支持这种方式.. 那么还有其他类似的方式吗? :)

【问题讨论】:

    标签: angular angular-material conditional-statements angular-components


    【解决方案1】:
    <button mat-button [color]=" boolean_condition ? 'accent' : 'primary'">
    

    这是一个使用材料颜色的简单示例。

    【讨论】:

      【解决方案2】:

      material design 内置了三种颜色,称为 primary、accent、warn 和 base 您传递给 color 的值将设置需要的类,在这种情况下,更改颜色的简单方法是定义一个类而不设置 color 属性

      style.scss

      .black {
        &.mat-raised-button.mat-button-base {
          background: black ;
          color:#fff ;
        }
      }
      
      .gray {
        &.mat-raised-button.mat-button-base {
          background: #ccc ;
          color:#555 ;
        }
      }
      .orange {
        &.mat-raised-button.mat-button-base {
          background: orange ;
          color:#fff ;
        }
      }
      

      模板

      <button mat-raised-button class="black">black</button>
      <button mat-raised-button class="gray">gray</button>
      <button mat-raised-button class="orange">orange</button>
      

      像这样通过ngClass指令和布尔属性设置条件的类基

       <button mat-raised-button 
              [ngClass]="{'black': isBlack , 'gray' : !isBlack}" (click)="isBlack =!isBlack" >
              click to toggle
       </button>
      

      demo ??

      【讨论】:

      • 我们已经有了自己的主题,颜色也出现了..关于条件的问题很简单......
      【解决方案3】:

      只能使用三元运算符

      [color]="coDeliverySlotView.slotId === bookedSlot.slotId ? 'black' : 'grey'"
      

      【讨论】:

      • ? 角度材质有一些预设颜色,例如 primary,accent,warn,为什么“黑色”、“灰色”不起作用,如果这是预设,你是正确的?
      猜你喜欢
      • 2021-06-22
      • 2018-01-04
      • 1970-01-01
      • 2020-01-19
      • 2019-06-04
      • 1970-01-01
      • 2019-03-04
      • 2018-02-17
      • 1970-01-01
      相关资源
      最近更新 更多