[英]Angular 2: Dynamically setting NgStyle and NgClass
我正在尝试通过在组件中调用将组件属性设置为目标样式的函数来动态设置img元素的样式。 但这是行不通的。
<div class="col-lg-2">
<a (click)="setColor('Black')">
<img class="img-fluid {{blackImgClass}}"
src="../assets/images/4ade25d4-3c31-45bd-a1e3-063b9f46c3d1_35.jpg">
</a>
</div>
<div class="col-lg-2 color-selection">
<a (click)="setColor('Stainless Steel')">
<img class="img-fluid {{stainlessImgClass}}"
src="../assets/images/62167c88-bf89-4848-acd6-c74d1970312a_35.jpg">
</a>
</div>
<div class="col-lg-2 color-selection">
<a (click)="setColor('White')">
<img class="img-fluid color-white {{whiteImgClass}}"
src="../assets/images/c79cd82b-37ea-43c4-b3ea-daceb08c4267_35.jpg">
</a>
</div>
该类在此函数的组件中设置:
private setColor(color: string) {
if (color == 'Black') {
this.productImages = this.product.images.black;
this.currentImage = this.product.images.black[0];
}
else if (color == 'White') {
this.productImages = this.product.images.white;
this.currentImage = this.product.images.white[0];
}
else if (color == 'Stainless Steel') {
this.productImages = this.product.images.stainless;
this.currentImage = this.product.images.stainless[0];
}
this.setCSSClass(color);
}
和setCSSClass():
private setCSSClass(color) {
if (color == 'Black') {
this.whiteImgClass = '';
this.blackImgClass = 'border-bottom: 3px solid #f96302';
this.stainlessImgClass = '';
this.selectionColor = color;
}
else if (color == 'White') {
this.whiteImgClass = 'border-bottom: 3px solid #f96302';
this.blackImgClass = '';
this.stainlessImgClass = '';
this.selectionColor = color;
}
else if (color == 'Stainless Steel') {
this.whiteImgClass = '';
this.blackImgClass = '';
this.stainlessImgClass = 'border-bottom: 3px solid #f96302';
this.selectionColor = color;
}
}
您要设置两次class
,其中之一将被忽略。 我也不确定带插值的绑定类是否可以工作。
首先,我将简化css,因为所有三种图像样式都具有一些基本属性-然后只需使用[ngStyle]
来设置颜色和所需的其他css属性。
的HTML
<img class="img-fluid basic-image-class" src="../assets/images/c79cd82b-37ea-43c4-b3ea-daceb08c4267_35.jpg" [ngStyle]="currentImageStyles">
的CSS
.basic-image-class: {border-bottom: 3px solid;}
码
public currentImageStyles: string = '';
private setCSSClass(color) {
if (color == 'Black') {
this.currentImageStyles = {'border-bottom-color: #f96302'};
}
else if (color == 'White') {
this.currentImageStyles = {'border-bottom-color: #999'};
}
else if (color == 'Stainless Steel') {
this.currentImageStyles = {'border-bottom-color: #ccc'};
}
您可以尝试这样-我为我的绝对要素动态设置top值,并使用[style.top.px] =“ top”进行设置,top是我的打字稿中的变量,在计算出它的值后会得到一个数字。 只要在这里设定你想要的
如果我很了解您,则需要将html更新为:
<img class="img-fluid color-white"
src="../assets/images/c79cd82b-37ea-43c4-b3ea-daceb08c4267_35.jpg"
class="color-white" [class.white-class]="yourCondition">
如果要添加“ white-class”,则“ yourCondition”应返回true,否则,则应返回false。
在您的CSS中:
image.white-class{
//DO your stuff
}
对于多个类绑定,可以使用ngClass,如下所述:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.