2017-08-29 137 views
1

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

<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(未找到)

未处理无极抑制:未能加载URL(%7B%7B% 20font.url%20%7D%7D);区域:;任务:Promise.then;价值:无法加载URL(%7B%7B%20font.url%20%7D%7D)

+0

相同的错误:/ 我认为角尝试评估之前的结合完成 –

+0

'URL表达({{字体.URL}})' – Swoox

+0

不,我甚至试图 <风格* ngIf = “字体” > –

回答

2

您可以创建在你的根组件为每个字体样式compononent,并导入符合以下条件:

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'; 
    } 
} 

只需添加应用程序逻辑来得到当前字体和开关添加新节点为需要的每个字体样式。

+0

感谢您的答案,但我的问题是,我们的客户可以上传自己的字体,所以我无法为ea创建组件可能的字体:( –

+2

好吧,我明白了。我会尝试使用jQuery来解决它,在获取当前客户端的字体后添加字体系列。指向网站内容中的静态文件。 –