我正在尝试使用d3实现自定义组件以可视化数据。我正在使用d3渐变来呈现颜色。
添加组件的另一个实例时,即使更改Input() colorList
,渐变的颜色也保持不变。有没有可能缺少的东西?
代码示例在这里: https://stackblitz.com/edit/spectrum-scale-component
//colorList = ['#9E0142', '#D53E4F','#090979']
<app-spectrum-scale
[data]="0.7"
[leftLabel]="'Feminine'"
[rightLabel]="'Masculine'"
[middleLabel]="'Neutral'"
[minVal]="-1"
[maxVal]="1"
[colorList]="['#9E0142', '#D53E4F','#090979']"
>
</app-spectrum-scale>
//colorList = "['#9E0142', '#D53E4F',
'#F46D43', '#FDAE61',
'#FEE08B', '#FFFFBF',
'#E6F598', '#ABDDA4',
'#66C2A5', '#6AA84F',
'#38761D']"
<app-spectrum-scale
[data]="0.55"
[leftLabel]="'Negative'"
[rightLabel]="'Positive'"
[middleLabel]="'Neutral'"
[minVal]="-1"
[maxVal]="1"
[colorList]="['#9E0142', '#D53E4F',
'#F46D43', '#FDAE61',
'#FEE08B', '#FFFFBF',
'#E6F598', '#ABDDA4',
'#66C2A5', '#6AA84F',
'#38761D']"
>
</app-spectrum-scale>
答案 0 :(得分:0)
解决方案是在组件初始化时向渐变样式添加唯一的ID。这将确保渲染的组件将选择正确的渐变。
此处的工作代码:https://stackblitz.com/edit/spectrum-scale-component
this._id ='id' + (new Date()).getTime();
然后您可以将此tempId分配给'rect'填充属性
var tempColorList = this.colorList
var tempId = this._id;
var grad = this._chart.append('defs')
.append('linearGradient')
.attr('id', tempId)
.attr('x1', '0%')
.attr('x2', '100%')
.attr('y1', '0%')
.attr('y2', '0%');
grad.selectAll('stop')
.data(tempColorList)
.enter()
.append('stop')
.style('stop-color', function(d){ return d; })
.attr('offset', function(d,i){
return 100 * (i / (tempColorList.length - 1)) + '%';
})
var gradValue = 'url(#' + tempId + ')'
var spectrum_bar = this._chart.append('rect')
.attr('class', 'bg-rect')
.attr('rx', 5)
.attr('ry', 5)
.style('opacity', 0.5)
// assign gradValue id here
.style('fill', gradValue)
.attr('height', 15)
.attr('width', this._barWidth)
.attr('x', 0)