Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Angular2 values in SVG linear gradient stop offset?

I want to use bind angular2 values in linear-gradient stop offset but its giving me errors. Can someone tell me how can I bind angular2 values in stop offset of linear-gradient as demonstrated below?

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;
 }
}

test-component.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>

Its giving me errors. I want to add gradient line with dynamic values. Please help.

enter image description here

@Gaunter I have updated/edited the code what you said, now the errors removed but still it seems that bar/gradient is constant based on the values determined in OnInit() function. I have checked the goodScore and dangerScore values in OnInit they are correct and not uniform. Any idea?

like image 679
Hassan Kashif Avatar asked Jun 13 '26 08:06

Hassan Kashif


1 Answers

I guess this is what you want:

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

You need either [attrname]="fieldName" or attrname="{{fieldName}}" to get Angular2 binding.
SVG elements don't have properties, therefore you need to do attribute binding, therefore the additional attr. prefix for binding to SVG elements.

like image 75
Günter Zöchbauer Avatar answered Jun 15 '26 00:06

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!