如何根据时间线选择更改 ngx-charts-line-chart 中的 xAxisTickFormatting?

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

默认情况下,刻度根据时间轴中的时间范围选择进行格式化。如果它跨越几天,它显示月份,如果它在一天内,它只显示时间。这太棒了!

现在我想本地化这些滴答声。我可以提供 xAxisTickFormatting 来完成这项工作,但我想根据时间范围选择进行格式化。 "MMM DD" 或 "HH:MM" 基于当前时间范围选择。

为此,我需要根据时间范围选择事件动态更改格式化功能。有这样的活动吗?或者还有其他方法可以实现吗?

在您的图表中,您可以在其他属性中声明

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

formatPercent 是在您的 .ts 文件中声明的函数(我使用的是 Angular),写成

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

如需参考,请查看文档 here

希望对您有所帮助。

看来,date是按照d3逻辑格式化的。它使用该滴答可用的精度。所以如果日期是12/15/2020 11:30:00,精度是分钟级的。类似地,如果日期是 12/15/2020 00:00:00,则精度为天级别。 现在我们可以相应地选择格式选项了。

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)));
}

现在这个函数可以用作

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