Custom font-awesome icon does not work when code is databound to view model


#1

I am able to use custom font icon by directly assigning the unicode value in xml file as below

<Label class="fa" text="&#xf015;"></Label>

This displays the font-awesome home icon as expected.
When I try to assign the unicode value from view-model it does not work.


<Label class="fa" text="&#xf015;"></Label>
<Label text="{{testIcon1}}" class="fa"/> 
<Label text="{{testIcon5}}" class="fa"/>
<Label text="{{testIcon6}}" class="fa"/>
<Label text="{{testIcon8}}" class="fa"/>

Here are the contents of the view-model

var observableModule = require("data/observable");
var drawerHomeViewModel = new observableModule.fromObject({
  testIcon1 : String.fromCharCode("\f015"),
  testIcon5 : String.fromCharCode("&#xf015;"),
  testIcon6 : "&#xf015;",
  testIcon8 : "static in code behind"
});

Could you please let me know how can I get it to work by assigning the value in code-behind view-model


#2

You use a “converter” function to do that, and you bind the function to your XML. Example:

When you setup your observable, you create a function. Here I call it ‘iconFromCode’, that will return the character from the hex code:

page.bindingContext = new Observable.fromObject({
    iconFromCode: function (code) {
      return String.fromCharCode(code);
    }
  });

Then in your XML, you bind this function to display the character itself:

<Label class="icon-font" text="{{ iconFromCode('0xf0a8') }}" />

Here’s a playground sample:

Notice 4 things in the playground sample:

  1. I defined a style in app.css (.icon-font) with the name of the font. That name is the name of the actual font. Eg if you open the font file (ttf) in the Font Book app (on the Mac), you can look up the internal name of the font.
  2. I placed the font file inside thefonts folder inside the app directory. {N} will read that automatically (…but I assume you already knew that…).
  3. Setup the converter function when you create your observable (in the JS file)
  4. And use the converter in your XML file (as I outlined above)

If you want to access icon fonts from within multiple files/pages in your app, you don’t need to define them individually in each file (when you create your observables). Instead, you would define the converter globally on the application in the app.js file, like so:

application.getResources().iconFromCode = function iconFromCode(code) {
	return String.fromCharCode(code);
}

And now you can just use this from the XML as above.

More about converters in bindings here:
https://docs.nativescript.org/core-concepts/data-binding#using-converters-in-bindings


#3

Follow the approach as @pentool suggested or use simply go nativescript-ngx-fonticon plugin that makes job even easier


#4

Thanks a lot @pentool for the detailed response


#5

@phcc
when you want to bind it from code behind, instead of using hex code &#xf015;
use unicode \uf015 that should work for you.