Angular-传递返回es6字符串的函数时,ngStyle返回[object Object]

时间:2019-03-20 11:29:35

标签: javascript angular ecmascript-6 ng-style

模板组件是这样的:

<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新型字符串可以做什么...

2 个答案:

答案 0 :(得分:0)

您可以尝试这样

SELECT time, 
       SUM( (username = 'jon')::int ) as cnt_jon,
       SUM( (username = 'bob')::int ) as cnt_bob
FROM My_With
GROUP BY time;

答案 1 :(得分:0)

您无需在setColor(hex?)函数中进行任何修改。只需删除单引号。例如:

this.selectedColor = `rgb(${hex === undefined ? this.randomColor() : hex})`;