How to change xAxisTickFormatting in ngx-charts-line-chart based on timeline selection?

In your chart, among the other attributes, you can declare

<ngx-charts-bar-horizontal-normalized
    ...
    [xAxis]="true"
    [xAxisTickFormatting]='formatPercent'
    ...
</ngx-charts-bar-horizontal-normalized>

formatPercent is a function declared in your .ts file (I'm using Angular) written like

formatPercent(val) {
    if (val <= 100) {
      return val + '%';
    }
  } 

For any reference check the documentation here

Hope this helps.


It looks like, date is formatted based on the d3 logic. It uses the precision available to that tick. So if date is 12/15/2020 11:30:00, precision is at minute level. Similarly if date is 12/15/2020 00:00:00, precision is at day level. Now we can choose the format options accordingly.

var locale = 'fr-FR'; // 'en-US'
function formatDate(value) {
  let formatOptions;
  if (value.getSeconds() !== 0) {
    formatOptions = { second: '2-digit' };
  } else if (value.getMinutes() !== 0) {
    formatOptions = { hour: '2-digit', minute: '2-digit' };
  } else if (value.getHours() !== 0) {
    formatOptions = { hour: '2-digit' };
  } else if (value.getDate() !== 1) {
    formatOptions = value.getDay() === 0 ? { month: 'short', day: '2-digit' } : { weekday: 'short', day: '2-digit' };
  } else if (value.getMonth() !== 0) {
    formatOptions = { month: 'long' };
  } else {
    formatOptions = { year: 'numeric' };
  }
  return new Intl.DateTimeFormat(locale, formatOptions).format(value);
}

var dates = ['12/15/2020 11:30:30', '12/15/2020 11:30:00', '12/15/2020 11:00:00', '12/15/2020 00:00:00', '12/13/2020 00:00:00', '12/01/2020 00:00:00', '01/01/2020 00:00:00'];
for (date of dates) {
  console.log(date, '=>', formatDate(new Date(date)));
}

Now this function can be used as

<ngx-charts-line-chart 
    [xAxis]="true" 
    [xAxisTickFormatting]="formatDate">
</ngx-charts-line-chart>

Tags:

Ngx Charts