Hello, I have the following child component that receives an object of type day through the @input
import { Component, OnInit, Input,OnChanges,SimpleChanges} from '@angular/core';
import { TiempoService } from './../../services/tiempo.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-graphs',
templateUrl: './graphs.component.html',
styleUrls: ['./graphs.component.css']
})
export class GraphsComponent implements OnInit, OnChanges {
@Input() dia:any[] =[];
public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels:string[] = [];
public barChartType:string = 'bar';
public barChartLegend:boolean = true;
public barChartData:any[] = [
{data: [], label: 'Temperatura'},
{data: [], label: 'Humedad'},
{data: [], label: 'Cobertura Nubosa'}
];
constructor() {
console.log(this.barChartData);
}
ngOnInit() {
for (let index = 0; index < this.dia.length; index++) {
this.barChartData[0].data.push(+this.dia[index][7]);
this.barChartData[1].data.push(+this.dia[index][15]);
this.barChartData[2].data.push(+this.dia[index][12]);
this.barChartLabels.push(this.dia[index][6]);
}
console.log(this.dia);
}
ngOnChanges(changes: SimpleChanges) {
console.log(changes.dia);
}
}
however this value changes depending on the parent component, implement the ngOnChanges method to notify me when changes occur, the console.log of the ngOnChanges (currentValue) method effectively changes the value depending on the change in the parent component, but how could I render the component and have the new variables reset when the day object changes so that the view is dynamically updated?
In your case you can do the following
In this way, the code of the setter will be executed every time a new value arrives to your component. Alternatively, you can run get on your
ngOnChanges
, but in that case you should check which input has changed and run it only if it is the day.Hello, I managed to solve the problem, first of all I had to call the set method every time a new value of _dia: any[] was generated, just as explained by @Ilsanchez, also doing a little research turns out that it is the best option when there are few variables that change, that is why the ngOnChanges method was not implemented,
This method is effectively executed every time the variable changes, however it did not modify the view since it had the same reference to the barChartLabels object, the solution in this case was to use Object.assign([], []); that changes the object reference and angular will be able to render the view with the new changes.