5

How do I use a font loader, such as WebFontLoader or FontFaceObserver, in Angular?

I'm not sure on what/where I need to import and how to use it in a component.

Waddas
  • 1,353
  • 2
  • 16
  • 28

3 Answers3

9

Do:
npm install webfontloader

Then in your component you can write like this:

app.component.ts:

import * as WebFont from 'webfontloader';
// ...
ngOnInit(){
  WebFont.load({/* your config...*/})
}
Mohi
  • 1,776
  • 1
  • 26
  • 39
  • 2
    You can use this anywhere, not limited to component. Run WebFont.load(...) only once in your code, and fonts will be available in all components. I am successfully loading this from a service constructor. – vanwinter Dec 14 '18 at 20:56
1

I've been configuring it in the index.html file itself (per the README on github)

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js">    
</script>
<script>
  WebFont.load({
    google: {
      families: ['Droid Sans', 'Droid Serif']
    }
  });
</script>
Rich
  • 882
  • 1
  • 8
  • 19
0

Use this approach:

  1. Install fontfaceobserver package from npm

    npm i fontfaceobserver
    
  2. Setup font observer (Note: you need to use this setup once in your app)

    import FontFaceObserver from 'fontfaceobserver';
    
    ngOnInit(): void {
        const font = new FontFaceObserver('My Family', {
          weight: 400
        });
    
        font.load().then(function () {
          console.log('Font is available');
        }, function () {
          console.log('Font is not available');
        });
    }
    

For implementing multiple fonts observer and also more optional configurations you can take a look at this official page: https://www.npmjs.com/package/fontfaceobserver

Hope this will help you.

Kamran Taghaddos
  • 452
  • 1
  • 10
  • 22