I am working in angular 6 project and I need to to give functionality of user uploaded font and use it.
I have also try below code :
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>
But this code show me an error at two place
1) cannot find name FontFace (FontFace object not supprted in angular)
2) Property 'fonts' does not exist on type 'Document'. (document.font object not supprted in angular)
Here is fiddle working in js but not working in typescript: http://jsfiddle.net/Mark_1998/xvpk0rnm/3/
Is there any alternative for load font dynamically in angular. please help me.
Assume your web font is an external css like Google Font, Adobe Typekit or your own css url.
In 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);
}
}
In 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>
Also, you may need to use ViewEncapsulation.None
if you want the style apply to sub-components.
Say you allow user to upload the font to firebase storage
and trigger a cloud functions
. Firebase allow you to write a new CSS to /tmp
and upload to firebase storage
and return a URL. Really depends which server and language you use.
In 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)
})
}
}
In app.component.html
,
<p [ngStyle]="{'font-family': 'barCode'}">Lorem ipsum</p>
This is not recommended yet as FontFace is an experimental technology and Working Draft
. There is cross-browser support issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With