【问题标题】:SVG + Angular2 code sample does not work with interpolationSVG + Angular2 代码示例不适用于插值
【发布时间】:2015-06-16 19:07:44
【问题描述】:

我的目标是将代码从 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>&lt;ellipse cx="100" cy="100" rx="80" ry="50" fill="red"&gt;&lt;/ellipse&gt;</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 angular


    【解决方案1】:

    SVG 元素不使用与 HTML 元素相同的命名空间。将 SVG 元素插入 DOM 时,需要使用正确的 SVG 命名空间插入它们。

    案例 1 有效,因为您将整个 SVG(包括 &lt;svg&gt; 标签)插入 HTML。浏览器会自动使用正确的命名空间,因为它看到了&lt;svg&gt; 标签并且知道该做什么。

    案例 2 不起作用,因为您只是插入了一个 &lt;ellipse&gt; 标记,而浏览器没有意识到它应该是使用 svg 命名空间创建的。

    如果您使用浏览器的 DOM 检查器检查两个 SVG,并查看 &lt;ellipse&gt; 标记的 namespace 属性,您应该会看到区别。

    【讨论】:

    • 如果无法插入整个 SVG,则需要使用 document.createElementNS() 等自行创建元素。
    【解决方案2】:

    您可以使用 HTML 元素的outerHtml,例如:

    @Component({
      selector: 'my-app',
      template: `
        <!--
          <svg xmlns='http://www.w3.org/2000/svg'><ellipse cx="100" cy="100" rx="80" ry="50" fill="red"></ellipse></svg>
        --> 
    
        <span [outerHTML]="graphics"></span>`
    })
    export class App {
      constructor() {
        this.graphics = this.getGraphics();
      }
    
      getGraphics() {
         // return an array of SVG elements (eventually...)
         var ell1 =
            '<svg><ellipse cx="100" cy="100" rx="80" ry="50" fill="red"></ellipse></svg>';
         return ell1;
      }
    }
    

    注意添加的字符串必须包含&lt;svg&gt;...&lt;/svg&gt;

    另见How can I add a SVG graphic dynamically using javascript or jquery?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 2023-04-05
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多