以语言环境在X轴上显示日期值取决于格式ngx-charts/d3
问题描述:
我有一个Web应用程序使用Angular v4.0.1和ngx-charts(使用d3)v5.1.2创建一个线图,其中x轴具有日期值。以语言环境在X轴上显示日期值取决于格式ngx-charts/d3
我的问题是,x轴不显示德国时间格式。所以我发现我可以如何设置d3的语言环境格式:
import * as d3 from "d3";
import * as formatDE from "d3-format/locale/de-DE.json";
import * as timeFormatDE from "d3-time-format/locale/de-DE.json";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
constructor() {
var formatBefore = d3.timeFormat("%A");
console.log('Before: '+formatBefore(new Date));
// output: Thursday -> OK
d3.formatDefaultLocale(formatDE);
d3.timeFormatDefaultLocale(timeFormatDE);
var formatAfter = d3.timeFormat("%A");
console.log('After: '+formatAfter(new Date));
// output: Donnerstag -> YES, nice
}
}
但是这对X轴有影响!日期和时间值仍然是英文格式。
答
虽然NGX-图表包装D3并不是所有的招数D3使用它。大多数NGX-图表组件具有连接到您自己的格式功能的xAxisTickFormatting
输入,例如:
<!-- some-component.html -->
<ngx-charts-line-chart ... [xAxisTickFormatting]="dateTickFormatting" ...>
</ngx-charts-line-chart>
// some-component.ts
function dateTickFormatting(val: any): string {
if (val instanceof Date) {
(<Date>val).toLocaleString('de-DE');
}
}