我有一系列从Sketch导出的.svgs (参见下面的示例),我已经注册到MatIconRegistry,并使用mat-icon组件显示。
然而,我注意到,在草图(导出为<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>发布于 2019-03-18 22:37:47
对于任何在未来偶然发现这一点的人:
从技术上讲,这个问题并不像我怀疑的那样与mat-icon有关。渲染svg的错误是由于草图的掩码和路径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)
}https://stackoverflow.com/questions/55190879
复制相似问题