In this article, we will see how we can use angular material with ngx-charts.
What is ngx-charts?
ngx-charts is the charting library built with angular and D3. It is used for data visualizations. It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis, and shape generators.
ngx-charts come with some default styles for the tooltip, labels, legends, etc.
In this article, we will override the tooltip styles to make it look like as in the material data-visualization guidelines.
Let’s start by creating a new material theme. We are assuming that angular material is already installed. We can create our custom angular theme as follow:-
As a next step, we will create scss mixin which will accept the angular material theme and override the tooltip style for us.
The mixin is like below:-
We are assuming here the tooltip is consistent throughout the application. So we are good to override the style with !important.
As you can see, we have access to angular material typography, mixins variables, etc. A couple of points to notice:-
- We are targetting the
.ngx-charts-tooltip
directly. But we can wrap it in our custom class wrapper to avoid collision with some other components in case we are writing a library. * As the tooltip caret is separate from the tooltip box so we need to override the background color for carets separately(.tooltip-caret.position-right etc). * We are usingmat-elevation
mixin from angular material to provide the box-shadow to the tooltip. You can read more about it here. * We are also using thesecondary-text
color from the material theme to make the sub-label looks like the secondary. * We are also getting the font-size from the material typography and making the sub-label as per the material data-visualization guidelines. Although we can also apply the mat-body-2 class in HTML(on span tag in below HTML file) as well I believe it's better to put the related code in the same class as have access to it. We can also override the other things axis labels, legend labels, etc with the material typography and theme.
The basic idea is to have the charts consistent with the material theme. So that if we implement multiple themes, then we can have our ngx-charts styles according to the other themes as well.
Our HTML file will look like:-
The end result will look like below:-
Stackblitz example:-
Top comments (0)