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

ger*_*rin 6 ngx-charts

默认情况下,刻度会根据时间轴中的时间范围选择进行格式化。如果平移显示几天,则显示月份,如果显示一天,则仅显示时间。这很棒!

现在,我要定位这些刻度。我可以提供xAxisTickFormatting来完成此操作,但是我想根据时间范围选择进行格式化。基于当前时间范围选择的“ MMM DD”或“ HH:MM”。

为此,我需要在时间范围选择事件中动态更改格式化功能。有这样的事件吗?还是有其他方法可以实现这一目标?

小智 6

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

<ngx-charts-bar-horizontal-normalized
    ...
    [xAxis]="true"
    [xAxisTickFormatting]='formatPercent'
    ...
</ngx-charts-bar-horizontal-normalized>
Run Code Online (Sandbox Code Playgroud)

formatPercent是在.ts文件(我使用Angular)中声明的函数,其编写方式如下

formatPercent(val) {
    if (val <= 100) {
      return val + '%';
    }
  } 
Run Code Online (Sandbox Code Playgroud)

有关任何参考,请在此处查看文档

希望这可以帮助。

  • 如果您将其更改为类似这样的函数 `formatPercent = (val) =&gt; { // 现在访问局部变量 }` 那么您也可以访问局部变量范围。这是能够有条件格式所需要的。否则这个答案不能完全解决问题 (3认同)

ger*_*rin 3

看起来,日期是基于 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)));
}
Run Code Online (Sandbox Code Playgroud)

现在这个函数可以用作

<ngx-charts-line-chart 
    [xAxis]="true" 
    [xAxisTickFormatting]="formatDate">
</ngx-charts-line-chart>
Run Code Online (Sandbox Code Playgroud)