Formatters
Index
Demo
Definition
Formatters
are functions that can be used to change and format certain column(s) in the grid. Please note that it does not alter the input data, it simply changes the styling by formatting the data differently to the screen (what the user visually see).
A good example of a Formatter
could be a column name isActive
which is a boolean
field with input data as True
or False
. User would prefer to simply see a checkbox as a visual indication representing the True
flag, for this behavior you can use Formatters.checkmark
which will use Material Design icon of mdi-check
when True
or an empty string when False
.
For a UI sample, scroll down below.
Provided Formatters
Slickgrid-Universal
ships with a few Formatters
by default which helps with common fields, you can see the entire list here.
Note you might not need a Formatter when a simple CSS style and class might be enough, think about using
cssClass
column property as much as possible since it has much better perf.
List of provided Formatters
arrayObjectToCsv
: Takes an array of complex objects converts it to a comma delimited string.arrayToCsv
: takes an array of text and returns it as CSV stringcheckmarkMaterial
use Material Design to display a checkmark iconcollection
: Looks up values from the columnDefinition.params.collection property and displays the label in CSV or string formatcomplexObject
: takes a complex object (with afield
that has a.
notation) and pull correct value, there are multiple ways to use it{ id: 'firstName', field: 'user.firstName', formatter: Formatters.complexObject}
, will display the user's first name{ id: 'firstName', field: 'user', labelKey: 'firstName', params: { complexField: 'user' }, ... }
{ id: 'firstName', field: 'user', params: { complexField: 'user.firstName' }, ... }
currency
: will help with currency other than dollar (ie€
), there are multipleparams
available for this formattercurrencyPrefix
,currencySuffix
,minDecimal
,maxDecimal
,numberPrefix
,numberSuffix
,decimalSeparator
,thousandSeparator
anddisplayNegativeNumberWithParentheses
the distinction between
numberPrefix
andcurrencyPrefix
can be seen when usingdisplayNegativeNumberWithParentheses
, for example if we have a value of-12.432
with theFormatters.currency
andparams: { currencyPrefix: '€', numberPrefix: 'Price ', numberSuffix: 'EUR' }
the output will be"Price (€12.432) EUR"
dateEuro
: Takes a Date object and displays it as an Euro Date format (DD/MM/YYYY)dateTimeEuro
: Takes a Date object and displays it as an Euro Date+Time format (DD/MM/YYYY HH:mm:ss)dateTimeShortEuro
: Takes a Date object and displays it as an Euro Date+Time (without seconds) format (DD/MM/YYYY HH:mm)dateTimeEuroAmPm
: Takes a Date object and displays it as an Euro Date+Time+(am/pm) format (DD/MM/YYYY hh:mm:ss a)dateIso
: Takes a Date object and displays it as an ISO Date format (YYYY-MM-DD)dateTimeIso
: Takes a Date object and displays it as an ISO Date+Time format (YYYY-MM-DD HH:mm:ss)dateTimeIsoAmPm
: Takes a Date object and displays it as an ISO Date+Time+(am/pm) format (YYYY-MM-DD h:mm:ss a)dateTimeShortIso
: Takes a Date object and displays it as an ISO Date+Time (without seconds) format (YYYY-MM-DD HH:mm)dateUs
: Takes a Date object and displays it as an US Date format (MM/DD/YYYY)dateTimeUs
: Takes a Date object and displays it as an US Date+Time format (MM/DD/YYYY HH:mm:ss)dateTimeShortUs
: Takes a Date object and displays it as an US Date+Time (without seconds) format (MM/DD/YYYY HH:mm:ss)dateTimeUsAmPm
: Takes a Date object and displays it as an US Date+Time+(am/pm) format (MM/DD/YYYY hh:mm:ss a)dateUtc
: Takes a Date object and displays it as a TZ format (YYYY-MM-DDThh:mm:ssZ)decimal
: Display the value as x decimals formatted, defaults to 2 decimals. You can pass "minDecimal" and/or "maxDecimal" to the "params" property.dollar
: Display the value as 2 decimals formatted with dollar sign '$' at the end of of the value.dollarColored
: Display the value as 2 decimals formatted with dollar sign '$' at the end of of the value, change color of text to red/green on negative/positive valuedollarColoredBoldFormatter
: Display the value as 2 decimals formatted with dollar sign '$' at the end of of the value, change color of text to red/green on negative/positive value, show it in bold font weight as wellhyperlink
: takes a URL cell value and wraps it into a clickable hyperlink<a href="value">value</a>
the cell value must contain (
ftp://abc
,http://abc
orhttps://abc
), if it doesn't then usefakeHyperlink
hyperlinkUriPrefix
: format a URI prefix into an hyperlinkicon
: to display an icon with defined CSS class name, useparams
to pass acssClass
propertyiconBoolean
: similar toicon
but will only be displayed on a Boolean truthy value, useparams
to pass acssClass
propertymask
: to change the string output using a mask, useparams
to pass amask
propertyexample:
{ field: 'phone', formatter: Formatters.mask, params: { mask: '(000) 000-0000' }}
multiple
: pipe multiple formatters (executed in sequence), useparams
to pass the list of formatters.example:
{ field: 'title', formatter: Formatters.multiple, params: { formatters: [ Formatters.lowercase, Formatters.uppercase ] }
percent
: Takes a cell value number (between 0.0-1.0) and displays a red (<50) or green (>=50) barpercentComplete
: takes a percentage value (0-100%), displays a bar following this logic:red
: < 30%,grey
: < 70%,green
: >= 70%
percentCompleteBar
: same aspercentComplete
but uses Bootstrap - Progress Bar with label.percentCompleteBarWithText
: Takes a cell value number (between 0-100) and displays SlickGrid custom "percent-complete-bar" with Text a red (<30), silver (>30 & <70) or green (>=70) barpercentSymbol
: Takes a cell value number (between 0-100) and add the "%" after the numberprogressBar
: Takes a cell value number (between 0-100) and displays Bootstrap "progress-bar" a red (<30), silver (>30 & <70) or green (>=70) bartranslate
: Takes a cell value and translates it (i18n). Requires an instance of the Translate Service:: `i18n: this.translatetranslateBoolean
: Takes a boolean value, cast it to upperCase string and finally translates it (i18n).tree
: Formatter that must be used when the column is a Tree Data column
Note: The list is certainly not up to date (especially for Dates), please refer to the Formatters export to know exactly which formatters are available.
Note all Date formatters are formatted using Tempo. There are also many more Date formats not shown above, simply visit the formatters.index to see all available Date/Time formats.
Usage
To use any of them, you simply need to import Formatters
from Slickgrid-Universal
and add a formatter: Formatters.xyz
(where xyx
is the name of the built-in formatter) in your column definitions as shown below:
Extra Arguments/Params
What if you want to pass extra arguments that you want to use within the Formatter? You can use params
for that. For example, let say you have a custom formatter to build a select list (dropdown), you could do it this way:
Using Multiple Formatters
SlickGrid only has 1 formatter
property but if you want to use more than 1 Formatter then you'll want to use the Formatters.multiple
and pass every Formatters inside your column definition params: { formatters: [] }
as shown below.
Note: please note that combining multiple Formatters has the side effect of cascading the formatted value
output to the next Formatter. So for example if you use the complexObject
and dollar
Formatters, you want to make sure to define them in the correct order in your formatters: []
array as shown below.
what if you want to avoid overwriting the
value
with a Custom Formatter?in that case you can have your Formatter return a FormatterResultObject, see below.
Custom Formatter
You could also create your own custom Formatter
by simply following the structure shown below.
TypeScript function signature
FormatterResultObject
The most common return result of a Formatter is a string
but you could also use the FormatterResultObject
which is an object with the interface signature shown below. The main difference is that it will allow to add CSS classes directly to the cell container instead of having to create an extra <div>
container and since that is the main cell container, you can add multiple Formatters to add/remove multiple CSS classes on that same container.
Example of a Custom Formatter with HTML string
For example, we will use our optional SVG icons .mdi
with a boolean
as input data, and display a (fire) icon when True
or a (snowflake) when False
. This custom formatter is actually display in the UI sample shown below.
Example with FormatterResultObject
instead of a string
FormatterResultObject
instead of a stringUsing this object return type will provide the user the same look and feel, it will actually be quite different. The major difference is that all of the options (addClasses
, tooltip
, ...) will be added the CSS container of the cell instead of the content of that container. For example a typically cell looks like the following <div class="slick-cell l4 r4">Task 4</div>
and if use addClasses: 'red'
, it will end up being <div class="slick-cell l4 r4 red">Task 4</div>
while if we use a string output of let say <span class="red">${value></span>
, then our final result of the cell will be <div class="slick-cell l4 r4"><span class="red">Task 4</span></div>
. This can be useful if you plan to use multiple Formatters and don't want to lose or overwrite the previous Formatter result (we do that in our project).
Example of Custom Formatter with Native DOM Element
Since version 7.x, you can now also return native DOM element instead of an HTML string. There are 2 main reasons for going with this approach:
CSP Safe by default, since it's native it is 100% CSP Safe (CSP: Content Security Policy)
Performance (the reasons are similar to point 1.)
since it's native it can be appended directly to the grid cell
when it's an HTML string, it has to do 2 extra steps (which is an overhead process) i. sanitize the string (when a sanitizer, for example DOMPurify) ii. SlickGrid then has to convert it to native element by using
innerHTML
on the grid cell
Demo
Note you could also use our helper
createDomElement
which allows to create a DOM element and pass properties likeclassName
in 1 liner (and it also works with intellisense). For examplecreateDomElement('span', { className: 'bold title', textContent: 'Hello World', title: 'some tooltip description' })
would equal to 4 lines of code.
More Complex Example
If you need to add more complex logic to a Formatter
, you can take a look at the percentCompleteBar Formatter
for more inspiration.
Common Formatter Options
You can set some defined common Formatter Options in your Grid Options through the formatterOptions
in the Grid Options (locally or globally) as seen below, and/or independently through the column definition params
(the option names are the same in both locations)
PostRender Formatter
SlickGrid also support Post Render Formatter (asynchronously) via the Column property asyncPostRender
(you will also need to enable in the grid options via enableAsyncPostRender
). When would you want to use this? It's useful if your formatter is expected to take a while to render, like showing a graph with Sparklines, and you don't want to delay rendering your grid, the Post Render will happen after all the grid is loaded.
To see it in action, from the 6pac samples, click here Code example:
A Better Solution is to use Custom Formatters as much as possible because using an Aurelia Components with asyncPostRender
are SLOW (you are warned). They are slow because they require a full cycle, cannot be cached and are rendered after each rows are rendered (because of their asynchronous nature), while Custom Formatters are rendered at the same time as the row itself since they are synchronous in nature.
UI Sample
Last updated