svg circle for angular2

Sha*_*raj 37 javascript typescript angular2-directives angular

我需要根据计算的百分比做一个进度弧,我创建了一个自定义指令来访问用户的svg属性,同时在我的模板中更新,我收到以下错误:

__CODE__ __CODE__ 等等..

我收到所有svg属性的上述错误.

以下是我在玉器中的代码:

progress-arc([size]="200", [strokeWidth]="20", [stroke]="red", [complete]="0.8")
Run Code Online (Sandbox Code Playgroud)

以下是我的指令代码:

import {Component,Input,AfterViewInit} from '@angular/core';

@Component({
  selector:'progress-arc',
  template:`
   <svg height="100" width="100">
      <circle fill="white"
          cx="{{parsedSize/2}}"
          cy="{{parsedSize/2}}"
          r="{{radius}}"
          stroke="{{stroke}}"
          stroke-width="{{strokeWidthCapped}}"
          stroke-dasharray="{{circumference}}"
          stroke-dashoffset="{{(1 - parsedComplete) * circumference}}"/>
  </svg>`,
  providers: [],
  directives: []
})
export class ProgressArc implements AfterViewInit {
 @Input('size') size:string;
 @Input('strokeWidth') strokeWidth:string;
 @Input('stroke') stroke:string;
  @Input('complete') complete:string;
  parsedStrokeWidth:number;
  parsedSize:number;
  parsedComplete:number;
  strokeWidthCapped:number;
  radius:number;
  circumference:number;

  ngAfterViewInit() {
    this.parsedSize = parseFloat(this.size);
    this.parsedStrokeWidth = parseFloat(this.strokeWidth);
    this.parsedComplete = parseFloat(this.complete);
    this.strokeWidthCapped = Math.min(this.parsedStrokeWidth, this.parsedSize / 2 - 1);
    this.radius = Math.max((this.parsedSize - this.strokeWidthCapped) / 2 - 1, 0);
    this.circumference = 2 * Math.PI * this.radius;
  }
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我哪里出错了?

Pie*_*Duc 96

为了绑定到SVG元素属性在角度2中,必须为它们添加前缀attr:

对于你的圈子,这将是:

<svg height="100" width="100">
      <circle fill="white"
          [attr.cx]="parsedSize/2"
          [attr.cy]="parsedSize/2"
          [attr.r]="radius"
          [attr.stroke]="stroke"
          [attr.stroke-width]="strokeWidthCapped"
          [attr.stroke-dasharray]="circumference"
          [attr.stroke-dashoffset]="(1 - parsedComplete) * circumference"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

我不完全确定它应该是[attr.stroke-width]或者[attr.strokeWidth],但是试一试

  • 它有效,但为什么有时我们需要attr.和somestines没有,这是没有意义的(编辑:我现在正在发布一个问题) (2认同)