Angular SVG作为模板

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

作者:唐伯虎点蚊香,如若转载,请注明出处:https://www.web176.com/angular13/24137.html

(0)
打赏 支付宝 支付宝 微信 微信
唐伯虎点蚊香的头像唐伯虎点蚊香
上一篇 2023年6月18日
下一篇 2023年6月18日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注