Angular SVG作为模板

2022-06-30 11:59 更新

SVG 作为模板

你可以在 Angular 应用程序中将 SVG 文件用作模板。当你使用 SVG 作为模板时,就可以像 HTML 模板一样使用指令和绑定。使用这些功能,你可以动态生成交互式图形。

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

SVG 语法示例

以下示例展示了将 SVG 用作模板的语法。

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​ 文件中:

<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"​)。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号