javascript - svg circle - 无法绑定(bind)到 cx,因为它不是已知的 native 属性

标签 javascript angular typescript angular2-directives

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

Can't bind to 'cx' since it isn't a known native property
Can't bind to 'cy' since it isn't a known native property

等..

我收到所有 svg 属性的此类错误。

下面是我在 jade 中的代码:

progress-arc([size]="200", [strokeWidth]="20", [stroke]="red", [complete]="0.8")

下面是我的指令代码:

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

谁能告诉我哪里出错了?

最佳答案

为了绑定(bind)到 Angular 中的 SVG 元素属性,您必须在它们前面加上 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>

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

当属性没有关联的属性时,需要使用attr前缀

关于javascript - svg circle - 无法绑定(bind)到 cx,因为它不是已知的 native 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38306363/

相关文章:

javascript - 如何通过输入字段更改 slider ?

javascript - 将 CSS A 类复制到 B 类

angular - 让 PrimeNG 进度条立即更新

javascript - 功能装饰器

javascript - W3 响应式导航栏不适用于我的应用程序

javascript - 了解如何结合使用 require js 和 text js 在主干应用程序中加载 html 模板

html - 如何在 Angular2 中实现 Google Analytics?

typescript - 运行 typescript-eslint-parser

angular - 在 Angular 的 http 订阅操作中使用 ngx-spinner

css - IE 11 Edge DevTools 没有计算样式