我在按钮中使用ngFor,在那里我从数据中得到了4个结果,并期望在HTML4中有4个按钮。如何为这个按钮应用4种不同的颜色?
P.S. 在ngFor颜色中,我收到obj:
我只使用Object.values从obj获取链接,并在this.img中分配colors,在this.img中,当单击4个按钮中的一个按钮时,使用它来显示每个图像。这就是为什么我需要申请每个按钮的背景色。
<div class="col-md-4 col-lg-4">
<img [src]="img">
</div>
<div>
<span class="title-description">Select color:</span>
<div class="row" style="margin-left: 0px;">
<button *ngFor="let colors of product.image" class="card ml-1"
(click)="changeColor(colors)"
style="height: 30px; width: 30px;">
</button>
</div>
</div>
changeColor(colors) {
this.img = Object.values(colors);
}发布于 2020-05-12 21:14:28
您需要将一个color属性添加到this.product.image中的每个对象中,其中包含一个颜色代码,然后您可以使用该属性来设置按钮的样式。例如:
products = [
{color: 'red', path: 'https://via.placeholder.com/150'},
{color: 'green', path: 'https://via.placeholder.com/250'},
{color: 'yellow', path: 'https://via.placeholder.com/350'},
{color: 'blue', path: 'https://via.placeholder.com/450'}
];然后,您可以使用ngStyle对每个按钮进行样式设置,使用以下颜色:
<button *ngFor="let product of products" [ngStyle]="{'background-color': product.color}" (click)="img = product.path"></button>
<img *ngIf="img" [src]="img">例如这里。
https://stackoverflow.com/questions/61761933
复制相似问题