使用 Angular 2 动态加载字体

Dynamic font loading with Angular 2

嘿,可以使用 Angular 2.4 动态加载字体吗?我尝试了以下但它不起作用。

<style>
  @font-face { font-family: '{{ font.name }}';
    src: url('{{ font.url }}')  format('woff'); }
</style>
@Component({
  selector: 'nova-font-loader',
  templateUrl: './template.html'
})
export class NovaFontLoaderComponent implements OnInit {

  private font;

  constructor() { }

  ngOnInit() {
    this.font = {
      url: 'test.woff',
      name: 'test'
    };
  }

}

它生成以下控制台输出:

GET http://localhost:4200/url(%7B%7B%20font.url%20%7D%7D) 404 (Not Found)

Unhandled Promise rejection: Failed to load url(%7B%7B%20font.url%20%7D%7D) ; Zone: ; Task: Promise.then ; Value: Failed to load url(%7B%7B%20font.url%20%7D%7D)

你可以为每个font-style创建一个组件,在你的根组件中导入符合条件:

Roboto 示例。

组件

注意:encapsulation: ViewEncapsulation.None对于这种情况非常重要。

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-font-roboto',
  templateUrl: './font-roboto.component.html',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./font-roboto.component.scss']
})
export class FontRobotoComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

SCSS

@font-face {
    font-family: 'Roboto';
    src: url("/assets/fonts/Roboto/Roboto-Regular.eot");
    /* IE9 Compat Modes */
    src: url("/assets/fonts/Roboto/Roboto-Regular.eot?#iefix") format('embedded-opentype'), /* IE6-IE8 */
    url('/assets/fonts/Roboto/Roboto-Regular.ttf') format('truetype'), /* Safari, Android, iOS */
}

@font-face {
    font-family: 'RobotoBold';
    src: url("/assets/fonts/Roboto/Roboto-Bold.eot");
    /* IE9 Compat Modes */
    src: url("/assets/fonts/Roboto/Roboto-Bold.eot?#iefix") format('embedded-opentype'), /* IE6-IE8 */
    url('/assets/fonts/Roboto/Roboto-Bold.ttf') format('truetype'), /* Safari, Android, iOS */
}

body { 
    font-family: 'Roboto', sans-serif;
}

根组件逻辑

模板 [HTML]

<div [ngSwitch]="fontType">
   <app-font-roboto *ngSwitchCase="'Roboto'"></app-font-roboto>
</div>

组件

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  fontType: string;

  ngOnInit(): void {
    this.fontType = 'Roboto';
  }
}

只需添加您的应用程序逻辑即可获取当前字体并在开关中为您需要的每种字体样式添加新节点。

您可以通过在 dom

中注入 css 轻松做到这一点
const fontUrl = '[get your font url here]';
this.styles = `
@font-face {
  font-family: 'font1';
  src: url(${fontUrl}) format('woff');
}
h1, h2, h3 {
  font-family: font1, sans-serif;
}`

const node = document.createElement('style');
node.innerHTML = this.styles;
document.body.appendChild(node);