【问题标题】:Unable to load custom SVG in mat-icon无法在 mat-icon 中加载自定义 SVG
【发布时间】:2019-08-06 23:58:50
【问题描述】:

我正在尝试在 MatIconRegistry 中加载自定义 SVG,并在我的组件中使用以下代码

  constructor(fb: FormBuilder,
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer) {
    this.matIconRegistry.addSvgIconInNamespace(
      'capp',
      'reassign',
      this.domSanitizer.bypassSecurityTrustResourceUrl('../../../../assets/images/reassign.svg')
    );
    this.form = fb.group({
      query: ''
    });
  }

但是当我用<mat-icon svgIcon="capp:reassign"></mat-icon>在浏览器中使用它时

我在控制台中收到以下错误

Error retrieving icon: Failed to construct 'URL': Invalid URL

我尝试了位于 assets 下的 images 文件夹中的 SVG 的各种相对路径,我尝试了 .//,并使其相对于 ../../ 的路径

我能够让它工作的唯一方法是指定完整的 URL,但这在部署时会有所不同,我理解 SVG 的路径应该是相对的

谁能给点建议?

【问题讨论】:

    标签: angular typescript angular-material


    【解决方案1】:

    我能够让它工作的唯一方法是指定完整的 URL,但这在部署时会有所不同

    您已经解决了这里的问题:它需要一个绝对 URL 而不是相对 URL。

    要解决“部署时不同”的问题,您可以考虑使用window.location.origin,只要应用的基本网址为/,它适用于任何环境。

    matIconRegistry.addSvgIconInNamespace(
      'capp',
      'reassign',
      domSanitizer.bypassSecurityTrustResourceUrl(window.location.origin + '/assets/images/reassign.svg')
    );
    

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 2020-04-18
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多