在 SVG 线性渐变停止偏移中绑定 Angular2 值?

Has*_*hif 3 javascript svg angular

我想在线性渐变停止偏移中使用绑定 angular2 值,但它给了我错误。有人能告诉我如何在线性渐变的停止偏移量中绑定 angular2 值,如下所示?

test.component.ts

import {Component, EventEmitter, ViewEncapsulation, Input, OnInit} from '@angular/core';


@Component({
selector: 'test-comp',
templateUrl: 'test-component.html',
encapsulation: ViewEncapsulation.None
})

export class TestComponent implements OnInit {

@Input() name: string;
@Input() flexScore: number;

protected goodScore: number;
protected dangerScore: number;
protected isComplete: boolean = false;

 ngOnInit() {
  this.goodScore = this.flexScore;
  this.dangerScore = 100 - this.goodScore;
  console.log(this.goodScore + ' ' + this.dangerScore);
  this.isComplete = true;
 }
}
Run Code Online (Sandbox Code Playgroud)

测试组件.html

<div class="individual-athlete-risk">
  <span id="name">{{name}}</span>
  <span id="score">{{flexScore}}</span>
</div>
<svg width="200" height="10" xmlns="http://www.w3.org/2000/svg">
  <defs>
      <linearGradient id="testGradient">
          <stop attr.offset="{{goodScore}}%" stop-color="blue"/>
          <stop attr.offset="{{dangerScore}}%" stop-color="red"/>
      </linearGradient>
  </defs>
  <rect fill="url(/test#testGradient)" x="0" y="0" width="200" height="9"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

它给了我错误。我想添加具有动态值的渐变线。请帮忙。

在此处输入图片说明

@Gaunter 我已经更新/编辑了您所说的代码,现在错误已删除,但似乎 bar/gradient 根据 OnInit() 函数中确定的值是恒定的。我已经检查了 OnInit 中的 goodScore 和 riskScore 值,它们是正确的并且不统一。任何的想法?

Gün*_*uer 6

我想这就是你想要的:

      <stop [attr.offset]="goodScore" stop-color="blue"/>
      <stop [attr.offset]="dangerScore" stop-color="red"/>
Run Code Online (Sandbox Code Playgroud)

您需要[attrname]="fieldName"attrname="{{fieldName}}"才能获得 Angular2 绑定。
SVG 元素没有属性,因此需要进行属性绑定,因此需要额外的attr.前缀来绑定到 SVG 元素。