February 28, 2018

How to dynamically change Font text in ionic app at runtime


First create and import your font file (woff files are ok) and basically you can setup two themes (one default font and another one with the new font) to change the font dinamically in your ionic app.

1. Import file into the project
If you are using a custom font file you should put your mynewfont file in the src/assets/font directory. I don't know which are the font file formats compatible for Ionic. Open Type Fonts (OTF) did not worked for me. Someone suggests TTF and SVG. I've used a Web Open Format Font (WOFF) file and it worked. 

2. Set the @fontface in the src/app/app.scss file

@font-face {
   
font-family: 'mynewfont';
    src: url('../assets/fonts/mynewfont.woff') format('woff');
   
font-weight: normal;
   
font-style: normal;
}
Set your font name family (for example mynewfont) but remember that it will be the font name for your entire project.

3. Import font path in variables.scss 
In some projects it is not necessary, but I would put it... 

$font-path: "../assets/fonts";

2. Create theme files
Inside yout project you need to create 2 scss files in the src/theme folder: theme.default.scss and theme.mynewfont.scss:
theme.default.scss

.default-theme {
}
theme.mynewfont.scss:

.newfont-theme {
  h1, h2, h3, h4, h5, h6, p, ion-item, ion-title, ion-label, ion-content, ion-row {
    font-family: 'MyNewFont' !important;
  }
}



3. Import theme sytles to variables.scss

@import "theme.default";
@import "theme.mynewfont";

4. Create a provider to get and set active theme following this tutorial from section 3: 


Enjoy it ;)