首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular mat-icon不使用蒙版渲染svg

Angular mat-icon不使用蒙版渲染svg
EN

Stack Overflow用户
提问于 2019-03-16 05:26:33
回答 1查看 1.7K关注 0票数 1

我有一系列从Sketch导出的.svgs (参见下面的示例),我已经注册到MatIconRegistry,并使用mat-icon组件显示。

然而,我注意到,在草图(导出为<defs>)中使用蒙版的任何图标都不能正确显示,有时甚至完全显示错误的图标。

我知道这是mat-icon的一个问题,因为文件在浏览器中呈现得很好。此外,当源文件不使用掩码时,mat-icon渲染也很好(但是我们不能保证svgs不会有掩码)

有没有人知道用Sketch或Angular解决这个问题的方法?

icon-registry.service.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
...
@Component({
  selector: 'my-component',
  template: `<mat-icon svgIcon="dot"></mat-icon>`,
  styleUrls: ['./icon.scss'],
  encapsulation: ViewEncapsulation.Emulated,
})
...

myModule.module.ts

代码语言:javascript
复制
...
@NgModule({
  declarations: [MyComponent],
  providers: [MyIconRegistry],
  imports: [CommonModule, MatIconModule, HttpClientModule],
  exports: [MyComponent],
})

icon-dot.svg

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2019-03-18 22:37:47

对于任何在未来偶然发现这一点的人:

从技术上讲,这个问题并不像我怀疑的那样与mat-icon有关。渲染svg的错误是由于草图的掩码和路径id不是唯一的。

因此,为了解决这个问题,我使用了ShadowDom封装,它使每个svg在其自己的DOM中是唯一的,并编写了我自己的注入。

myComponent.component.ts

代码语言:javascript
复制
...
@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)
  }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55190879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档