簡體   English   中英

Angular 材料(組件)中的條件按鈕顏色屬性

[英]Conditional button color attr in Angular Material (Components)

我有一個需要輸入的組件。 @Input() coDeliveryCandidates: DeliverySlotView[];

這在模板中使用:

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

顏色屬性將字符串作為值,我想做類似的事情:

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

在這里,我使用與 ngClass 相同的語法,但我想它不支持這種方式.. 那么還有哪些其他類似的方式呢? :)

可以只使用三元運算符

[color]="coDeliverySlotView.slotId === bookedSlot.slotId ? 'black' : 'grey'"
<button mat-button [color]=" boolean_condition ? 'accent' : 'primary'">

這是使用材料顏色的一個可能的簡單示例。

material design 內置了三種顏色,稱為primary、accent、warn 和base,您傳遞給color 的值將設置需要的類,在這種情況下,更改顏色的簡單方法是定義一個類而不設置color 屬性

樣式文件

.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>

演示🚀🚀

我用了這個方法

零件

isActive = false;

html

<input type="checkbox" [(ngModel)]="isActive">    

<button mat-raised-button [color]="isActive ? 'warn' : 'warn'">
        {{isActive ? 'warn' : 'warn'}}
</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM