javascript - 在 SVG 线性渐变停止偏移中绑定(bind) Angular2 值?

标签 javascript angular svg

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

测试.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;
 }
}

测试组件.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>

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

enter image description here

@Gaunter 我已经更新/编辑了您所说的代码,现在错误已删除,但根据 OnInit() 函数中确定的值,条形/渐变似乎仍然是常量。我检查了 OnInit 中的 goodScore 和 dangerScore 值,它们是正确的并且不统一。有什么想法吗?

最佳答案

我想这就是你想要的:

      <stop [attr.offset]="goodScore" stop-color="blue"/>
      <stop [attr.offset]="dangerScore" stop-color="red"/>

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

关于javascript - 在 SVG 线性渐变停止偏移中绑定(bind) Angular2 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41073950/

相关文章:

javascript - JS 函数 : prototype overriding vs prototype extension

angular - 是否可以添加动态类以在 Angular 2 中托管?

angular - 如何等待异步订阅完全填充全局变量?

svg - 如何从 svg 中的 <a> 元素中的 <text> 中删除悬停时的下划线

javascript - 将 Openlayers 3 和 proj4js 与 RequireJS 结合使用

javascript - Mozilla firefox 中的黑盒

javascript - 在悬停时将文本附加到链接标题?

javascript - 使用 mat-checkbox 看不到 Angular 复选框

javascript - 如何在 SVG 中显示文本的工具提示?

javascript - d3.js 强制折叠标签