angular - 通过 MdIconRegistry 和 DomSanitizer 从 Assets 中检索图标

标签 angular angular-material

您好,我的项目中有一个 components/home-component/home.component.htmlcomponents/home-component/home.component.ts。我还有一个 svg 文件 assets/homenav/home_icon.svg。我正在 home.component.ts 的构造函数中加载图标:

import { Component, OnInit } from '@angular/core';
import { MdIconRegistry } from '@angular/material';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
    moduleId: module.id,
    templateUrl: 'home.component.html',
    styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

    constructor(private iconRegistry: MdIconRegistry, private sanitizer: DomSanitizer) {
        iconRegistry.addSvgIcon('home', sanitizer.bypassSecurityTrustResourceUrl('assets/homenav/home_icon.svg'));        
    }

    ngOnInit() { }

}

如果我运行我的应用程序,应用程序本身可以正常工作。虽然图标没有被渲染。我正在加载这样的图标:

<md-icon class="homeNavIcon" color="primary" svgIcon="home"></md-icon>

没有错误消息或任何其他提示。如果我输入 http://localhost:4200/assets/homenav/home_icon.svg 作为 url,图标会正确显示在浏览器中。

此外,如果我在 HomeComponent 构造函数中设置断点并尝试在控制台中调用 iconRegistrycall,我会得到:

enter image description here

我还尝试将 url 更改为:

iconRegistry.addSvgIcon('home', sanitizer.bypassSecurityTrustResourceUrl('/../../../assets/homenav/home_icon.svg'));  

和其他几个没有运气的组合。如果我将 home.component 直接放入 app 文件夹,它也似乎可以工作

我是否提供了错误的 url 或我是否遗漏了其他内容。

更新:

我意识到如果图标在我的其他项目中正确显示,svgElement 也是空的。我还想概述一下我的 @NgModule:

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    MaterialModule,
    MdCardModule,
    HttpModule,
    BrowserAnimationsModule
  ],
  providers: [
    AuthGuard,
    AuthenticationService,
    UserService,
    // providers used to create fake backend
    fakeBackendProvider,
    MockBackend,
    BaseRequestOptions
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

更新 2:

正如我已经假设的那样,MdIconRegistry 中的图标从未加载过。我可以插入任何废话作为 Url,这不会引发任何错误。即:

iconRegistry.addSvgIcon('home', 
sanitizer.bypassSecurityTrustResourceUrl('LoremIpsumblabla')); 

这个调用不会抛出任何异常,而在另一个项目中我得到:

Failed to load resource: the server responded with a status of 404 (Not Found) :4200/LoremIpsumblabla

最佳答案

尝试改变这个路径

'./assets/homenav/home_icon.svg'

关于angular - 通过 MdIconRegistry 和 DomSanitizer 从 Assets 中检索图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45905807/

相关文章:

angular - 如何隐藏 Material 输入

angular - 如何禁用 Angular Material Slide 切换组件上的拖动选项

angular - TypeScript (Angular) - 逐行读取文本文件

angular - 在 Angular 的 HttpInterceptor 中进行实际的 http 调用之前,调用另一个 http api(不进行拦截)

angular - 将 MDBootstrap 添加到 Angular 项目

html - 管理 Angular 组件高度以适应屏幕的最佳方法

node.js - 如何避免 npm install/update 意外?

angularjs - Angular Material slider 如何设置刻度值

html - 如何在 Angular 中将空的必需输入字段警报颜色显示为蓝色?

angular - mat-table - 如果任何列的内容很长,则溢出父级 div