0👍
please try this:
import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute,Params} from '@angular/router';
import {Chart} from 'chart.js'
import {WeatherService} from '../../services/weather.service';
import {Weather} from '../../models/weather';
@Component({
selector: 'app-viewcities',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.css'],
providers:[]
})
export class ChartComponent implements OnInit {
chart = [];
public title: String;
public weathers: Weather[];
public weathersCity: Weather[];
public identity;
public token;
public url: String;
public page;
public prev_page;
public next_page;
public cityPassed;
public temperature=[];
public dates=[];
labels: any = [];
data: any = [];
constructor(
private _route:ActivatedRoute,
private _router:Router,
private _weatherService:WeatherService) { }
ngOnInit() {
//this.showCityWeather();
this.alertMessage();
}
alertMessage(){
alert("By now the chart is not rendered until the console it´s open or you change the zoom(CTRL)+scroll down/up")
}
showCityWeather(){
var localStorageRetrieve=localStorage.getItem("cityToView");
var city=localStorageRetrieve;
this._weatherService.showWheatherByCity(city).subscribe(
response=>{if(!response){
this._router.navigate(['/']);
}else{
this.weathersCity = response;
console.log(this.weathersCity)
//loop the object and add the data to the chart's array
for(let i=0;i<this.weathersCity.length;i++){
this.temperature.push(this.weathersCity[i].temperature)
this.dates.push(this.weathersCity[i].date) }
}},
error => {
let errorMessage = <any>error;
if (errorMessage !== null) {
let body = JSON.parse(error._body);
console.log(body);
}
}
)
}
showchart = false;
ngAfterViewInit() {
this.showCityWeather();
this.chart=new Chart('canvas',{
type:'bar',
data:{
labels:this.dates,
datasets:[{
label: 'Temp. in Cº',
data:this.temperature,
backgroundColor: [
],
borderColor: [
],
borderWidth: 5
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:false
}
}]
}
}
})
setTimeout(() => {
this.showchart = true;
},100)
}
}
<div class="chart" *ngIf="showchart">
<canvas #canvas id="canvas">{{ chart }}</canvas>
</div>
- Chartjs-Chartjs improvement display label
- Chartjs-Chart.js manage the height of the graph to match the data
Source:stackexchange.com