Since you appear to be using the segment buttons for navigation, I’m not sure if what I am thinking will work in your case, but here’s how I do something similar to GitHub’s preview function:
From the user’s perspective, the toggle buttons cause the write and preview part of the DOM to appear to swap, which sounds somewhat similar to what you are seeking.
However I get the following error:
EXCEPTION: Uncaught (in promise): TypeError: undefined is not an object (evaluating ‘_this.lineCanvas.nativeElement’)
When I close error dialog, the solutions seems to be exactly what I need.
Do you have any idea about the error message?
I was not getting the error message without the buttons.
Yes, that’s one of those tricky Angular pitfalls. I assume you’re using @ViewChild to try to grab that canvas element. You can’t do that with a normal property if the item in question is coming and going via ngIf. I believe you can work around it using a custom setter, something like this:
@ViewChild('lineCanvas') set painLineCanvas(plc: ViewContainerRef) {
this._painLineCanvas = plc;
}
lineChart: any;
painRecords = [];
constructor(public navCtrl: NavController,
public storage: Storage,
public dateProvider: DateProvider) {
}
getReports() {
return this.storage.get('painRecords').then(data => {
return JSON.parse(data);
});
}
ionViewDidEnter() {
Promise.all([this.getReports()]).then(records => {
let labels:any[] = [];
let painScores:any[] = [];
let painRecords = records[0];
for(let i = 0; i < painRecords.length; i++){
let date: Date = new Date(painRecords[i].date);
labels.push(date.getDate() + " " + this.dateProvider.returnMonth(date.getMonth()));
painScores.push(Number(painRecords[i].painScore));
}
this.lineChart = new Chart(this. _painLineCanvas.nativeElement, {
// parameters for the chart
})
this.storage.get('painRecords').then(data => {
let records = JSON.parse(data);
this.painRecords = [];
for(let i = records.length - 1; i >=0; i--){
let date = records[i].date;
records[i].date = this.dateProvider.getDate(date);
this.painRecords.push(records[i]);
}
})
}
I forgot to change lineCanvas to _painLineCanvas. However when I did, I got another error: Property ‘nativeElement’ does no exist on type ‘ViewContainerRef’. This was type error in my editor.
Got it. ionViewDidEnter is not the right place to be trying to access the canvas (it may not exist in the DOM then). Try moving the creation of lineChart out of there and into the painLineCanvas setter like so:
@ViewChild('lineCanvas') set painLineCanvas(plc: ViewContainerRef) {
this._painLineCanvas = plc;
if (plc) {
this.lineChart = new Chart(plc.getNativeElement(), {
// parameters for the chart
});
}
}
More often. Every time the pain segment is activated. If that’s not what you want, you could probably switch from using ngIf to binding [hidden] instead (or some class with display: none). I expect that would keep both the pain and anxiety segments (and whatever others you have) always in the DOM.