Angular2渲染器:渲染了Svg rect但未在页面中显示

时间:2017-10-17 09:54:18

标签: javascript angular svg ionic3

我想使用SVG创建一个条形图,并使用rect作为条形图。

相关代码如下:

条形图-one.html

   <svg #svgone width="400" height="250" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 250">
    <g #abcd></g>
</svg>

条形图-one.ts

 import { Component, Renderer2, ViewChild, ElementRef } from '@angular/core';

    @Component({
    selector: 'barchart-one',
    templateUrl: 'barchart-one.html'
    })
    export class BarchartOneComponent {
    @ViewChild('abcd') 
    private abcd: ElementRef;  
    constructor(private renderer: Renderer2) {}

    ngAfterViewInit() {
        for (var i = 1; i < 8; i++) {
            let height = Math.floor(Math.random() * (140 - 110)) + 110;
            const rect = this.renderer.createElement('rect');
            this.renderer.setAttribute(rect, 'height', height);
            this.renderer.setAttribute(rect, 'rx', '6');
            this.renderer.setAttribute(rect, 'ry', '6');
            this.renderer.setAttribute(rect, 'width', '12');
            this.renderer.setAttribute(rect, 'x', (i*50)+20);
            this.renderer.setAttribute(rect, 'y', (220-height));
            this.renderer.appendChild(this.abcd.nativeElement, rect);
            console.log(rect);
        };
    }
    }

svg渲染的结果:

<g>


<rect height="126" rx="6" ry="6" width="12" x="70" y="94"></rect>
<rect height="122" rx="6" ry="6" width="12" x="120" y="98"></rect>
<rect height="124" rx="6" ry="6" width="12" x="170" y="96"></rect>
<rect height="116" rx="6" ry="6" width="12" x="220" y="104"></rect>
<rect height="139" rx="6" ry="6" width="12" x="270" y="81"></rect>
<rect height="123" rx="6" ry="6" width="12" x="320" y="97"></rect>
<rect height="137" rx="6" ry="6" width="12" x="370" y="83"></rect>
</g>

即使正确呈现了rect的代码,预期结果也不会显示在页面中。

2 个答案:

答案 0 :(得分:2)

您不能使用createElement创建SVG元素,您必须使用createElementNS并传递SVG名称空间,即http://www.w3.org/2000/svg作为第一个参数。

this.renderer.createElementNS('http://www.w3.org/2000/svg', 'rect');

答案 1 :(得分:0)

这是一个古老的问题,但是,也许将来有人会发现它有用。有一个名为ngx-svg的Angular模块,它允许轻松创建多个SVG元素并将其绘制在站点上。与这些元素的相互作用也很多。

您的html代码如下所示-

<svg-container containerId="barChart" height="500">
  <svg-rect height="126" width="12" color="#000" x="70" y="94"></svg-rect>
  <svg-rect height="122" width="12" color="#000" x="120" y="98"></svg-rect>
  <svg-rect height="124" width="12" color="#000" x="170" y="96"></svg-rect>
  <svg-rect height="116" width="12" color="#000" x="220" y="104"></svg-rect>
  <svg-rect height="139" width="12" color="#000" x="270" y="81"></svg-rect>
  <svg-rect height="123" width="12" color="#000" x="320" y="97"></svg-rect>
  <svg-rect height="137" width="12" color="#000" x="370" y="83"></svg-rect>
</svg-container>

上面的代码将自动创建并绘制所需的图表。