我在angular 6项目中工作,我需要提供用户上传字体的功能并使用它。
我也尝试下面的代码:
var junction_font = new FontFace('example_font_family', 'url(https://fonts.gstatic.com/s/gloriahallelujah/v9/LYjYdHv3kUk9BMV96EIswT9DIbW-MIS11zM.woff2)');
junction_font.load().then(function (loaded_face) {
document.fonts.add(loaded_face);
}).catch(function (error) {
console.log('error : ', error);
});
HTML:
<p style="example_font_family">Lorem Ipsum</p>
但是这段代码在两个地方显示错误
1)找不到名称Font Face(角度不支持Font Face对象)
2)“文档”类型中不存在属性“fonts”。 (angular.font对象不支持角度)
这里是小提琴工作在js但不工作的打字稿:http://jsfiddle.net/Mark_1998/xvpk0rnm/3/
是否有角度动态加载字体的替代方法。请帮我。
假设您的网络字体是外部css,如Google Font,Adobe Typekit或您自己的CSS网址。
在app.component.ts
,
import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Change whatever your like
public link = "https://fonts.googleapis.com/css?family=Noto+Sans+TC"
constructor(
private sanitizer: DomSanitizer
) {
this.sanitizer = sanitizer;
}
getFontCSS() {
return this.sanitizer.bypassSecurityTrustResourceUrl(this.link);
}
}
在app.component.html
<link [href]="getFontCSS()" rel="stylesheet">
<p [ngStyle]="{'font-family': 'Noto Sans TC'}">Lorem ipsum</p>
<p [ngStyle]="{'font-family': 'Arial'}">Lorem ipsum</p>
此外,如果您希望样式应用于子组件,则可能需要使用ViewEncapsulation.None
。
假设您允许用户将字体上传到firebase storage
并触发cloud functions
。 Firebase允许您将新的CSS写入/tmp
并上传到firebase storage
并返回一个URL。真的取决于您使用的服务器和语言。
在app.component.ts
,
import { Component } from '@angular/core';
declare let FontFace: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
this.loadFont()
}
loadFont() {
let customFont = new FontFace('barCode', 'url(https://fonts.gstatic.com/s/felipa/v6/FwZa7-owz1Eu4F_AT96F.woff2)');
customFont.load().then((res) => {
document['fonts'].add(res);
}).catch((error) => {
console.log(error)
})
}
}
在app.component.html
,
<p [ngStyle]="{'font-family': 'barCode'}">Lorem ipsum</p>
这不推荐,因为FontFace是一种实验技术和Working Draft
。有跨浏览器支持问题。