填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫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").