javascript - Angular mat-icon 不使用蒙版渲染 svg
问题描述
我有一系列.svgs
从 Sketch 导出的(参见下面的示例),我已注册到MatIconRegistry
,并正在使用该mat-icon
组件进行显示。
但是我注意到在 Sketch 中使用遮罩的任何图标(导出为<defs>
)都不能正确显示,有时会完全显示错误的图标。
我知道这是一个问题,mat-icon
因为文件在浏览器中呈现良好。mat-icon
当源文件不使用掩码时也可以正常渲染(但是我们不能保证不会svgs
有掩码)
有谁知道在 Sketch 或 Angular 中解决此问题的方法?
icon-registry.service.ts
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
@Injectable({
providedIn: 'root',
})
export class MyIconRegistry {
constructor(
private matIconRegistry: MatIconRegistry,
private domSanitizer: DomSanitizer) {
this.matIconRegistry.addSvgIcon(
'dot',
'path/to/icon-dot.svg'
)
}
}
myComponent.component.ts
...
@Component({
selector: 'my-component',
template: `<mat-icon svgIcon="dot"></mat-icon>`,
styleUrls: ['./icon.scss'],
encapsulation: ViewEncapsulation.Emulated,
})
...
myModule.module.ts
...
@NgModule({
declarations: [MyComponent],
providers: [MyIconRegistry],
imports: [CommonModule, MatIconModule, HttpClientModule],
exports: [MyComponent],
})
icon-dot.svg
<svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 53.2 (72643) - https://sketchapp.com -->
<title>icon-dot</title>
<desc>Created with Sketch.</desc>
<defs>
<circle id="path-1" cx="12" cy="12" r="8"></circle>
</defs>
<g id="Icons" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="icon-dot">
<mask id="mask-2" fill="white">
<use xlink:href="#path-1"></use>
</mask>
<g id="Mask" fill-rule="nonzero"></g>
<g id="Blue/" mask="url(#mask-2)" fill="#0A4ACE">
<rect id="Rectangle" x="0" y="0" width="24" height="24"></rect>
</g>
</g>
</g>
</svg>
解决方案
对于将来遇到此问题的任何人:
mat-icon
正如我所怀疑的那样,这个问题在技术上并不存在。渲染中的错误svg
是由于 Sketch 的非唯一掩码和路径id
。
所以为了解决这个问题,我使用了 ShadowDom 封装,它使每个svg
在自己的 DOM 中都是独一无二的,并编写了我自己的注入。
myComponent.component.ts
...
@Component({
...
encapsulation: ViewEncapsulation.ShadowDom,
})
...
ngOnChanges(changes: SimpleChanges){
this.iconRegistry.getNamedSvgIcon(this.name).pipe(take(1)).subscribe(
svg => {
this.setSvgElement(svg)
},
(err: Error) => console.warn(`Error retrieving icon: ${err.message}`)
)
}
private setSvgElement(svg: SVGElement){
this.elementRef.nativeElement.shadowRoot.appendChild(svg)
}
推荐阅读
- c# - 如何在 Vue + ASP.NET 中实现数据排序?
- mysql - JDBC将数据从txt文件插入MySql表
- bash - 外部函数 bash 中的 Scriptsteps 计数器
- node.js - 如何纠正此错误“TypeError:EthereumTransaction 不是构造函数”?
- c++11 - 如何使用按位运算将 3 个整数值编码为 uint16_t?
- oracle - 在比较 oracle db 中的模式时,需要忽略标识列的“开始于”序列
- sql - 如果任何 SQL 在循环内失败,如何使 ANT 构建失败
- php - 无法更新表单数据laravel
- java - 使用 Java 流根据日期间隔对列表数据进行分组并对金额字段求和
- http - 颤振http.get没有执行