Angular2渲染器:渲染了Svg rect但未在页面中显示 [英] Angular2 Renderer: Svg rect is rendered but not showing in page
本文介绍了Angular2渲染器:渲染了Svg rect但未在页面中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用SVG创建一个条形图,矩形作为条形。
I want to create a bar chart using SVG with rect as the bar.
相关代码如下:
barchart-one.html
barchart-one.html
<svg #svgone width="400" height="250" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 250">
<g #abcd></g>
</svg>
barchart-one.ts
barchart-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的代码,预期结果也不会显示在页面中。
The expected result is not showing in page even though the code for rect is correctly rendered.
推荐答案
您无法使用createElement创建SVG元素,您必须使用createElementNS并传递SVG名称空间,即 http://www.w3.org/2000/svg 作为第一个参数。
You cannot create SVG elements with createElement, you must use createElementNS and pass the SVG namespace i.e. http://www.w3.org/2000/svg as the first parameter.
this.renderer.createElementNS('http://www.w3.org/2000/svg', 'rect');
这篇关于Angular2渲染器:渲染了Svg rect但未在页面中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文