我的目标是将代码从 Angular 1.3 转换为 Angular 2(两种情况下都使用 SVG)。
我尝试了以下简单的测试代码,它适用于不涉及插值的情况 #1,但在情况 #2(使用插值)和 AFAICS 中不起作用,生成的 SVG 代码中的唯一区别是包含元素中的额外属性:class="ng-binding"
有没有办法抑制前面的类属性,或者有其他解决方案?
顺便说一句,我无法完全正确地设置格式(抱歉)。
HTML网页内容:
<html>
<head>
<title>SVG and Angular2</title>
<script src="quickstart/dist/es6-shim.js"></script>
</head>
<body>
<!-- The app component created in svg1.es6 -->
<my-svg></my-svg>
<script>
// Rewrite the paths to load the files
System.paths = {
'angular2/*':'/quickstart/angular2/*.js', // Angular
'rtts_assert/*': '/quickstart/rtts_assert/*.js', // Runtime assertions
'svg': 'svg1.es6' // The my-svg component
};
System.import('svg');
</script>
</body>
</html>
JS文件内容:
import {Component, Template, bootstrap} from 'angular2/angular2';
@Component({
selector: 'my-svg'
})
@Template({
//case 1 works:
inline: '<svg><ellipse cx="100" cy="100" rx="80" ry="50" fill="red"></ellipse></svg>'
//case 2 does not work:
//inline: "<svg>{{graphics}}</svg>"
})
class MyAppComponent {
constructor() {
this.graphics = this.getGraphics();
}
getGraphics() {
// return an array of SVG elements (eventually...)
var ell1 =
'<ellipse cx="100" cy="100" rx="80" ry="50" fill="red"></ellipse>';
return ell1;
}
}
bootstrap(MyAppComponent);
最佳答案
SVG 元素不使用与 HTML 元素相同的命名空间。将 SVG 元素插入 DOM 时,需要使用正确的 SVG 命名空间插入它们。
案例 1 有效,因为您要插入整个 SVG,包括 <svg>
标签,放入 HTML 中。浏览器会自动使用正确的命名空间,因为它看到了 <svg>
标记并知道该做什么。
情况 2 不起作用,因为您只是插入一个 <ellipse>
标签和浏览器没有意识到它应该是用 svg 命名空间创建的。
如果您使用浏览器的 DOM 检查器检查两个 SVG,并查看 <ellipse>
标签的 namespace
属性(property),你应该看到差异。
关于SVG + Angular2 代码示例不适用于插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29572011/