【问题标题】:FontAwesome 5 setup in Angular 6 with Angular Materials using the <mat-icon> directive使用 <mat-icon> 指令在 Angular 6 中使用 Angular Materials 设置 FontAwesome 5
【发布时间】:2019-01-21 22:26:43
【问题描述】:

基线:

  • Angular 6.0.3
  • 角材料 6.4.2
  • “@fortawesome/angular-fontawesome”:“^0.1.1”
  • “@fortawesome/fontawesome-svg-core”:“^1.2.2”
  • "@fortawesome/free-solid-svg-icons": "^5.2.0"

    所以我已经安装了 angular-fontawesome 并且我试图让 &lt;mat-icon&gt; 指令工作,但它没有。我不清楚如何注册字体,或者我是否也需要。我正在寻找一个例子,说明有人使用带角度的新字体真棒,以及使用&lt;mat-icon&gt; 指令来显示图标所需的内容。如果我按照 angular-font-awesome GitHub 页面上的说明进行操作,一切正常,但他们使用的是这样的标签:&lt;fa-icon icon="coffee"&gt;&lt;/fa-icon&gt;

请有人完成设置,以便我可以使用&lt;mat-icon&gt; 指令来渲染这些设置。

【问题讨论】:

标签: angular6 font-awesome-5 angular-material-6


【解决方案1】:

直接取自this link,在我的项目中实施和工作,这些是我遵循的步骤。

  1. 安装相关的 FontAwesome 库

    npm i @fortawesome/fontawesome-svg-core
    npm i @fortawesome/free-brands-svg-icons
    npm i @fortawesome/free-regular-svg-icons
    npm i @fortawesome/free-solid-svg-icons
    
  2. 创建图标服务

    import { Injectable } from '@angular/core';
    import { MatIconRegistry } from '@angular/material';
    import { DomSanitizer } from '@angular/platform-browser';
    import { IconDefinition } from '@fortawesome/fontawesome-svg-core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class IconService {
      constructor(private _iconRegistry: MatIconRegistry, private _sanitizer: DomSanitizer) {}
      addSvg(icon: IconDefinition) {
        const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${icon.icon[0]} ${icon.icon[1]}">
            <path d="${icon.icon[4]}" />
          </svg>`;
    
        this._iconRegistry.getNamedSvgIcon(icon.iconName, icon.prefix).subscribe(
          () => {
            //Ok, icon already exists
          },
          () => {
            //Error, not found, add it
            this._iconRegistry.addSvgIconLiteralInNamespace(
              icon.prefix,
              icon.iconName,
              this._sanitizer.bypassSecurityTrustHtml(svg)
            );
          }
        );
      }
    }
    
  3. 添加您需要的图标,这应该根据需要完成以防止捆绑膨胀

    // In app.component or relevant component requiring icon
    import { faGoogle } from '@fortawesome/free-brands-svg-icons';
    /*...*/
    constructor(
      _iconService: IconService
    ) {
      _iconService.addSvg(faGoogle); // add icon to library
    }
    
  4. 使用你的图标

    <mat-icon svgIcon="fab:google"></mat-icon>
    

【讨论】:

  • 这应该被标记为正确答案!谢谢!
  • 但在mat-icon-button 中的使用令人不安。如果您设置较小的按钮,您的图标剪辑,如果您通过 css 按钮设置较小的图标保持不变。
猜你喜欢
  • 2019-03-19
  • 2019-04-20
  • 2018-05-17
  • 1970-01-01
  • 2019-08-07
  • 2019-11-21
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多