我有4张卡片。选择(点击)卡我想突出显示卡或更改卡的背景。能告诉我如何实现这一目标吗?
<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
来使用标志来设置每张卡的背景。
由于你的所有卡都几乎相同,我使用*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;
}
万一你使用最新的角度材料,并希望更改你的card的背景颜色悬停和点击/活动状态:也许这种懒惰的方法有助于:
.mat-card:hover {
background-color: yellow;
}
.mat-card:active {
background-color: red;
}
...并且不要忘记定义'onclick'属性。
<mat-card (click)="yourFn()">