文章内容
2024/11/9 0:59:36,作 者: 黄兵
Angular 将 SVG 代码渲染成图片的方法
在组件中使用 bypassSecurityTrustHtml 转换
在组件使用 bypassSecurityTrustHtml 转换 svgIcon,但是不直接赋值给 svgIcon,而是在模板中使用:
import { Component, ChangeDetectorRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ProjectService } from './project.service'; // 请根据你的实际路径修改
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
})
export class YourComponent {
dataSource: any[] = [];
displayedColumns: string[] = ['index', 'name', 'icon', 'show', 'url', 'project', 'action'];
constructor(
private projectService: ProjectService,
private sanitizer: DomSanitizer,
private changeDetectorRefs: ChangeDetectorRef
) {}
// 获取项目菜单数据
public getAllProjectMenu() {
this.projectService.getAllProjectMenu().subscribe(
(res) => {
this.dataSource = res;
this.changeDetectorRefs.detectChanges();
},
(error) => {
console.error(error);
}
);
}
}
在模板中使用 SafeHtml
在模板中,你可以通过 DomSanitizer 直接将 SVG 内容渲染为安全的 HTML。
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8 w-100">
<ng-container matColumnDef="icon">
<th mat-header-cell *matHeaderCellDef> 菜单图标</th>
<td mat-cell *matCellDef="let element">
<!-- 使用 innerHTML 渲染转换后的 SVG -->
<div [innerHTML]="sanitizer.bypassSecurityTrustHtml(element.svgIcon)"></div>
</td>
</ng-container>
</table>
总结:
如果你不能修改类型,只需要在模板中使用 bypassSecurityTrustHtml() 将 SVG 内容转化为安全的 HTML 并渲染。
其它相关推荐:
1、Angular [innerHTML] styles不起作用
2、angular robots.txt sitemap.xml
评论列表