詳細ガイド
テンプレート構文

SVG をテンプレートとして使用

AngularアプリケーションでSVGファイルをテンプレートとして使用できます。 SVGをテンプレートとして使用する場合、HTMLテンプレートと同様にディレクティブとバインディングを使用できます。 これらの機能を使用して、動的にインタラクティブなグラフィックを生成します。

SVG 構文例

次の例は、SVGをテンプレートとして使用するための構文を示しています。

src/app/svg.component.ts

      
import {Component} from '@angular/core';@Component({  standalone: true,  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 ファイルに追加します。

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" を使用しています。