如何突出显示 md-card 或更改角度 2 中 med-card 的背景颜色

How to highlight md-card or change the backgroud color of md-card in angular2

我有 4 张 md 卡。在选择(单击)卡片时,我想突出显示卡片或更改卡片的背景。你能告诉我如何实现吗

<div class="ui-g">
      <div class="ui-g-3"><md-card  [style.background]="'#fbeafc'"><md-card-content><h3>Component1</h3>
        </md-card-content></md-card></div>
    <div class="ui-g-3"><md-card  [style.background]="'#fbeafc'"><md-card-content><h3>Component2</h3>
        </md-card-content></md-card></div>
    <div class="ui-g-3"><md-card  [style.background]="'#fbeafc'"><md-card-content><h3>Component3</h3>
        </md-card-content></md-card></div>
     <div class="ui-g-3"><md-card  [style.background]="'#fbeafc'"><md-card-content><h3>Component4</h3>
        </md-card-content></md-card></div>
    </div>

一个简单的方法是,将您的代码更改为以下内容

组件

//declare a class member in component
private isSelected:string;

//in the component define a function
setColor(value){
  this.isSelected=value;
}

样式

//in css
.color1{
  background:#fbeafc
}

.color1{
  background:#fbeafc
}

.color1{
  background:#fbeafc
}

.color1{
  background:#fbeafc
}

模板

<div class="ui-g">
  <div class="ui-g-3">
    <md-card  [class.color1]="isSelected === 'color1'" (click)="setColor('color1')">
      <md-card-content>
        <h3>Component1</h3>
      </md-card-content>
    </md-card>
  </div>
  <div class="ui-g-3">
    <md-card  [class.color2]="isSelected === 'color2'" (click)="setColor('color2')">
      <md-card-content>
        <h3>Component2</h3>
      </md-card-content>
    </md-card>
  </div>
  <div class="ui-g-3">
    <md-card  [class.color3]="isSelected === 'color3'" (click)="setColor('color3')">
      <md-card-content>
        <h3>Component3</h3>
      </md-card-content>
    </md-card>
  </div>
  <div class="ui-g-3">
    <md-card  [class.color4]="isSelected === 'color4'" (click)="setColor('color4')">
      <md-card-content>
        <h3>Component4</h3>
      </md-card-content>
    </md-card>
  </div>
</div>

希望这对您有所帮助。请在使用前验证代码。我还没有测试过

如果您希望同时突出显示多张卡片,您可以维护一个标志数组来跟踪选择和取消选择了哪张卡片。然后,我们可以通过ngClass使用flags来设置每张卡片的背景。

因为你们所有的卡片几乎都一样,我使用*ngFor来避免代码重复。

html:

<div class="ui-g">
  <div class="ui-g-3" *ngFor="let x of [1, 2, 3, 4]; let i = index">
    <md-card  [ngClass]="{'highlight' : selected[i], 'not-highlight' : !selected[i]}"
              (click)="onSelect(i)">
      <md-card-content>
        <h3>Component {{x}}</h3>
      </md-card-content>
    </md-card>
  </div>
</div> 

ts:

selected = [false, false, false, false];

onSelect(index){
  // console.log(index);
  this.selected[index] = !this.selected[index];
}

css:

.highlight{
  background: skyblue;
}

.not-highlight{
  background: #fbeafc;
}

Plunker demo

以防万一您使用最新的 angular material 并想要更改 card 的背景颜色以进行悬停和 clicked/active 状态:也许这种懒惰的方法有帮助:

.mat-card:hover {
  background-color: yellow;
}

.mat-card:active {
  background-color: red;
}

...并且不要忘记定义 'onclick' 属性。

<mat-card (click)="yourFn()">