Angular ngFor 在 svg 中给出错误,即使它编译

Angular ngFor gives an error in svg, even though it compiles

我正在尝试对线进行递归以制作图表,但控制台中出现奇怪的错误,即使它在节点上工作。这是我们的模板:

<svg height = "200" width = "300">
    <g *ngFor = "let node of nodes; let i = index; let last = last;">
      <line 
        [attr.x1] = nodes[i].x
        [attr.y1] = nodes[i].y
        [attr.x2] = nodes[i+1].x
        [attr.y2] = nodes[i+1].y
      />
      <line *ngIf = last
        [attr.x1] = nodes[i].x
        [attr.y1] = nodes[i].y
        [attr.x2] = nodes[i].x
        [attr.y2] = nodes[i].y
      />
    </g>
  </svg>

这是打字稿:

export class VisitsGraphComponent implements OnInit {
  nodes = [
    { x: 0, y: 0 },
    { x: 40, y: 120 },
    { x: 80, y: 80 },
    { x: 120, y: 90 },
    { x: 160, y: 40 }
  ]
  ngOnInit():void {

  }
}

我尝试简单地使用 node.x 并将其放入 ngOnInit() 中,但出现完全相同的错误:

Cannot read property 'x' of undefined

对于节点数组的最后一项,您仍在尝试访问节点[i+1],但没有元素,因此它会抛出错误。试试 ngif else block 或 nodes[i+1]?.x

你绑定了错误的数据 将 nodes[i].x 更改为 > node[i].x 所以尝试实现这个html文件

.html

<svg height = "200" width = "300">
<g *ngFor = "let node of nodes; let i = index; let last = last;">
  <line 
    [attr.x1] = node[i].x
    [attr.y1] = node[i].y
    [attr.x2] = node[i+1].x
    [attr.y2] = node[i+1].y
  />
  <line *ngIf = last
    [attr.x1] = node[i].x
    [attr.y1] = node[i].y
    [attr.x2] = node[i].x
    [attr.y2] = node[i].y
  />
</g>