Using ngx-charts in a grid

In one of my recent work projects, we are using charts within a Bootstrap grid. After updating from Chartist to ngx-charts, we had a severe issue with the charts, which suddenly overlapped each other. I would like to share my investigation and solution for this issue.

Why we changed to ngx-charts

When building more and more charts, we realized that Chartist did not provide some features we needed, in particular click handlers. Although I had implemented a click handler for simple diagrams, adding one for multi-dimensional data seemed daunting and error-prone. So ngx-charts came into play, supporting many more chart types and click handlers. Also the integration seemed easier for an Angular application.

The ngx-charts demo site also suggested responsive behaviour as there was an option Fit Container, which is actually the default behaviour when no size is specified. But when changing our charts to ngx-charts we suddenly had non-responsive charts, overlapping each other, causing some distress.

The problem

I have created a github repository and a sample application to illustrate the issue. It uses a Bootstrap grid with gray columns. The column contains a chart inside of a wrapping div element (see app.component.html). In the actual implementation this div contains a chart type switch. But to see the issue, a simple div is sufficient.

The chart has now a fixed size of 600x400 and ignores the width of the grid column. This is not the behaviour we expected. Especially for multiple columns, we see overlapping charts.

A simple solution

In the ngx-charts examples, absolute positioning is used for the chart, which has an actual container available to fill. In our case, only the width is defined, the wrapping div has no height set initially. So filling this available space is not possible for the library, instead a default size is used.

When using a defined height of 200px, the chart behaves as expected. Please see my sample application to test yourself.

Using a fixed height may not be the ideal solution. One approach could also be to maintain an aspect ratio. This could be achieved with an element resize listener which adjusts the height.