ed-*_*ter 0 css font-awesome ngfor google-material-icons angular
我有一个动态图标列表,这些图标显示在右侧栏中。图标会根据用户的操作传递到侧边栏中。使用图标显示此动态图标数组ngFor。
不幸的是,有些图标来自Font Awesome,有些来自Google Material。
<!--Font Awesome-->
<i class="{{myIcon}}"></i>
<!--Material-->
<md-icon>{{myIcon}}></md-icon>
<!--Or-->
<i class="material-icon">{{myIcon}}</i>
Run Code Online (Sandbox Code Playgroud)
看到它们不完全匹配,如何使用ngFor使其只显示图标名称的字符串就可以同时显示两种。
我为您提供解决方案。我只是实现了这一点。
现在,我知道您只是要求* ngFor之间的内容,以便根据图标字符串动态选择并渲染适当的图标,但是我将记录完整的解决方案,包括为其他人注册很棒的字体。
让我们从顶部开始,确保您的标头中包含字体真棒CSS。您可以在http://fontawesome.io/get-started/中通过fontawesome通过电子邮件发送其CDN版本的链接,并将其包含在标题中。
<script src="https://use.fontawesome.com/c26638a4cc.js"></script>
Run Code Online (Sandbox Code Playgroud)
接下来,在您的app.module中创建并注册fontawesome的别名。您可以通过首先导入以下内容来做到这一点:
import { MdIconModule, MdIconRegistry } from '@angular/material';
Run Code Online (Sandbox Code Playgroud)
不要忘记在您的提供商中包括MdIconRegistry
providers: [
...
MdIconRegistry,
...
],
Run Code Online (Sandbox Code Playgroud)
然后让我们像这样在AppModule中向MdIconRegistry注册fontawesome。
constructor(...,
public mdIconRegistry: MdIconRegistry) {
mdIconRegistry.registerFontClassAlias('fontawesome', 'fa');
...
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我们已经完成的工作允许我们在应用程序中使用真棒字体图标,如下所示:
<md-icon class="some-class" fontSet="fa" fontIcon="fa-trophy"></md-icon>
Run Code Online (Sandbox Code Playgroud)
现在让我们回答原始问题,即如何仅基于图标字符串动态显示材质设计图标或超棒字体图标。
为此,我将使用以'fa-'前缀开头的超棒字体图标。如果我们对此感到满意,那么我可以检查“ fa-”并使用它来适当地设置fontSet和fontIcon。
<md-list-item *ngFor="let menuitem of menuList">
<button md-button ...>
<md-icon [fontSet]="menuitem.icon.substr(0,3) === 'fa-' ? 'fa' : ''"
[fontIcon]="menuitem.icon.substr(0,3) === 'fa-' ? menuitem.icon : ''"
[ngClass]="{'your-fa-custom-class': true }">
<span>{{ menuitem.name }} </span>
</button>
Run Code Online (Sandbox Code Playgroud)
ngClass包含.your-fa-custom-class,您可以在其中专门更改字体真棒图标的字体大小。
你们都准备好了!