Angular - ngStyle return [object Object] when function that returns a es6 string 被传递
Angular - ngStyle return [object Object] when function that returns a es6 string is passed
模板组件是这样的:
<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>
基本上我的组件必须更改按钮 (click)
事件的背景颜色:
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();
}
}
在渲染中,<div>
显示:
<div _ngcontent-c1="" class="colorBlock" ng-reflect-ng-style="[object Object]"></div>
而 {{ selectedColor }}
正确更新字符串。
我仍在尝试弄清楚 ES6 新类型的字符串可以做什么...
你可以这样试试
<div class="colorBlock" [style.background]="selectedColor"></div>
您的 setColor(hex?)
函数几乎不需要修改。只需删除单引号。例如:
this.selectedColor = `rgb(${hex === undefined ? this.randomColor() : hex})`;
模板组件是这样的:
<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>
基本上我的组件必须更改按钮 (click)
事件的背景颜色:
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();
}
}
在渲染中,<div>
显示:
<div _ngcontent-c1="" class="colorBlock" ng-reflect-ng-style="[object Object]"></div>
而 {{ selectedColor }}
正确更新字符串。
我仍在尝试弄清楚 ES6 新类型的字符串可以做什么...
你可以这样试试
<div class="colorBlock" [style.background]="selectedColor"></div>
您的 setColor(hex?)
函数几乎不需要修改。只需删除单引号。例如:
this.selectedColor = `rgb(${hex === undefined ? this.randomColor() : hex})`;