The template component is this:
<ul class="list-group list-group-horizontal">
<li class="list-group-item no-border" *ngFor="let color of colorList">
<button class="btn btn-link" (click)="setColor(color.hex)">{{ color.name }}</button>
</li>
</ul>
{{ selectedColor }}
<div class="colorBlock" [ngStyle]="{'background-color': selectedColor }"></div>
Basically my component has to change the background-color on the event (click)
of the button:
export class BlockColorChangerComponent implements OnInit {
title = 'Change the color of the block.';
selectedColor: any = this.setColor();
colorList = [
{name: 'Red', hex: '255,0,0'},
{name: 'Blue', hex: '0,0,255'},
{name: 'Green', hex: '0,255,0'},
{name: 'Yellow', hex: '255,255,0'},
{name: 'Pink', hex: '255,200,255'},
{name: 'Random'}
];
randomColor() {
return Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255);
}
setColor(hex?) {
this.selectedColor = `rgb('${hex === undefined ? this.randomColor() : hex}')`;
}
constructor() { }
ngOnInit() {
this.setColor();
}
}
On the render, the <div>
shows:
<div _ngcontent-c1="" class="colorBlock" ng-reflect-ng-style="[object Object]"></div>
While {{ selectedColor }}
updates the string correctly.
I'm still trying to figure out what ES6 new type of string can do...
you need little modification in your setColor(hex?)
function. just remove single quotations. Ex:
this.selectedColor = `rgb(${hex === undefined ? this.randomColor() : hex})`;