填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

模板中的 SVG

SVG in templates

可以在 Angular 中可以把 SVG 用作有效模板。下面提及的所有模板语法都适用于 SVG 和 HTML。在 SVG 1.12.0 规范中可以了解更多信息。

It is possible to use SVG as valid templates in Angular. All of the template syntax below is applicable to both SVG and HTML. Learn more in the SVG 1.1 and 2.0 specifications.

包含本章代码片段的工作实例参阅现场演练 / 下载范例

See the现场演练 / 下载范例for a working example containing the code snippets in this guide.

为什么要用 SVG 作为模板,而不是简单地把它作为图片添加到你的应用中呢?

Why would you use SVG as template, instead of simply adding it as image to your application?

当你用 SVG 作为模板时,可以像使用 HTML 模板一样使用指令和绑定。这意味着你可以动态生成交互式图形。

When you use an SVG as the template, you are able to use directives and bindings just like with HTML templates. This means that you will be able to dynamically generate interactive graphics.

相关的语法范例,请参阅下面的范例代码段:

Refer to the sample code snippet below for a syntax example:

import { Component } from '@angular/core'; @Component({ selector: 'app-svg', templateUrl: './svg.component.svg', styleUrls: ['./svg.component.css'] }) export class SvgComponent { fillColor = 'rgb(255, 0, 0)'; changeColor() { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); this.fillColor = `rgb(${r}, ${g}, ${b})`; } }
src/app/svg.component.ts
      
      import { Component } from '@angular/core';

@Component({
  selector: 'app-svg',
  templateUrl: './svg.component.svg',
  styleUrls: ['./svg.component.css']
})
export class SvgComponent {
  fillColor = 'rgb(255, 0, 0)';

  changeColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    this.fillColor = `rgb(${r}, ${g}, ${b})`;
  }
}
    

把以下代码添加到你的 svg.component.svg 文件中:

Add the following code to your svg.component.svg file:

<svg> <g> <rect x="0" y="0" width="100" height="100" [attr.fill]="fillColor" (click)="changeColor()" /> <text x="120" y="50">click the rectangle to change the fill color</text> </g> </svg>
src/app/svg.component.svg
      
      <svg>
  <g>
    <rect x="0" y="0" width="100" height="100" [attr.fill]="fillColor" (click)="changeColor()" />
    <text x="120" y="50">click the rectangle to change the fill color</text>
  </g>
</svg>
    

你可以看到这里使用了事件绑定语法 click() 和属性绑定语法( [attr.fill]="fillColor" )。

Here you can see the use of a click() event binding and the property binding syntax ([attr.fill]="fillColor").