Ng2 charts on Angular 9 not responsive

๐Ÿ‘:0

You can use ternary operators for options to check if you are on a small screen, if you use the scriptable options they are re evaluated every time the screen size changes, for the height of the canvas you can use basic CSS media querys

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    plugins: {
      title: {
        display: true,
        text: 'title',
        font: {
          size: (ctx) => window.innerWidth > 700 ? 24 : 12
        }
      },
      legend: {
        display: (ctx) => window.innerWidth > 700
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>

Fiddle to easily see difference on resize: https://jsfiddle.net/Leelenaleee/2bde1mph/3/

Leave a comment