首页 > 解决方案 > 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>

标签: javascriptangularsvgangular-materialmaterial-design

解决方案


对于将来遇到此问题的任何人:

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)
  }

推荐阅读