Search code examples
data-bindingknockout.js

Knockout binding a font awesome icon to a property


I'm attempting to display a font awesome icon based on a property whilst looping through a knockout observable array.

Current code:

<tbody data-bind="foreach: TimeToPutAwaySummary">
    <tr class="noOfPeopleRequiredRow">
        <td data-bind="text: $data.IsOptimumNoOfPeople ? '***' + $data.NoOfPeopleRequiredText + '***' : $data.NoOfPeopleRequiredText">
        </td>
        <td style="text-align: right" data-bind="text: $data.Time"></td>
    </tr>
</tbody>

This currently works such that it outputs:

1 Person Required
*** 2 Person Required ***
3 Person Required
4 Person Required
5 Person Required

However, I want to display a font awesome icon instead of the '***' i.e. something like this:

1 Person Required
(font awesome icon) 2 Person Required
3 Person Required
4 Person Required
5 Person Required

I've tried the following but that doesn't display an icon:

<tbody data-bind="foreach: TimeToPutAwaySummary">
    <tr class="noOfPeopleRequiredRow">
        <td data-bind="text: $data.IsOptimumNoOfPeople ? '***' + $data.NoOfPeopleRequiredText + '***' : $data.NoOfPeopleRequiredText">
            <span data-bind="visible: IsOptimumNoOfPeople"><i class="fa fa-spinner" aria-hidden="true"></i></span>
        </td>
        <td style="text-align: right" data-bind="text: $data.Time"></td>
    </tr>
</tbody>

I also tried to replace the span tag with a p tag.


Solution

  • you're using <td data-bind="text: $data....> on your td, this wil overwrite all content inside the element thus your icon-span-tag is ignored & removed. try moving the data-bind away from your td like following copy/paste code:

    <td>
     <span data-bind="text: $data.IsOptimumNoOfPeople ? '***' + $data.NoOfPeopleRequiredText + '***' : $data.NoOfPeopleRequiredText"></span>
     <span data-bind="visible: IsOptimumNoOfPeople"><i class="fa fa-spinner" aria-hidden="true"></i></span>
    </td>
    

    Or better yet just remove the data-bind on your td since that's going to be replaced with your font-awesome icon.. :)