Asaf Bello
Asaf Bello

Reputation: 91

Dynamic font in angular 10

i have two question.

  1. is it possible to read and get an array of the folder assets/fonts?

  2. I have a feature in my project of uploading fonts, the question is, can i have dynamic fonts? which means they are NOT declared in SCSS. i want to declare them dynamically using [ngStyle] or some other way.

i tried the following:

          <mat-select class="customSelect" panelClass="" disableOptionCentering="true" formControlName="font">
            <mat-option  [ngStyle]="testFont">TEST</mat-option>
          </mat-select>

and in .ts file

  testFont = {
    '@font-face' : `{
      font-family: DIN Office Medium Italic; // will  replace with variable
      src: url(assets/fonts/ + 'DINOffc-MediIta.ttf'); // will  replace with variable
    }`
}

is it possible? i couldn't find any solution for dynamic font at all.

Upvotes: 1

Views: 521

Answers (1)

Andrew Howard
Andrew Howard

Reputation: 3072

I have recently just done it on mine but it wasn't easy.

You can't just read the contents of a folder of fonts though. I suggest you have either an api or local json file that you can read in. The following data structure would work:

"fonts": [
    {
      "id": 564654746747,
      "refName": "Press Start 2P",
      "fontUpload": null,
      "filePath": "PressStart2P-Regular.ttf"
    },
    {
      "id": 1607016789736,
      "refName": "Nerko One",
      "fontUpload": null,
      "filePath": "font1607016803471.ttf"
    },
    {
      "id": 1609847399144,
      "refName": "Roboto Slab",
      "fontUpload": null,
      "filePath": "font1609847418669.ttf"
    }
  ]

And then to dynamically render those new fonts in your browser, send the array to this method which will create an on-the-fly stylesheet:

generateFontCss(arr)
        {
            var myEle = document.getElementById("fontStylesheet");
            if (myEle) {
                document.getElementById("fontStylesheet").remove();
            }

            let result = "<style>";
            result = result + "body{}";

            arr.forEach(element => {
            result = result + "@font-face {";
            result = result + "font-family: 'font"+element.id+"';";
            result = result + "src: url('"+this.gameDomain()+"/"+element.filePath+"') format('truetype');";
            result = result + "font-weight: normal;";
            result = result + "font-style: normal;";
            result = result + "}";
            });
            result = result + "</style>";
                        
            const head = document.getElementsByTagName('head')[0];
                const style = document.createElement('style');
                style.type = 'text/css';
                style.id = "fontStylesheet";
                style.appendChild(document.createTextNode(result));
                head.appendChild(style);
        }

Upvotes: 1

Related Questions