I'm using ng2-charts in my ionic 2 project to draw a line chart. I need to access the chart datapoint collection in the (chartClick) event. For that I need access to the base chart.js object for the chart. Is there a way I can access the chart object?
HTML:
<base-chart class="chart"
[data]="chartData"
[labels]="chartLabels"
[options]="lineChartOptions"
[colours]="lineChartColours"
[legend]="lineChartLegend"
[chartType]="chartType"
(chartClick)="chartClicked($event)"></base-chart>
TypeScript:
chartClicked(e: any) {
var chart = //reference to base chart object.
var points = chart.getPointsAtEvent(e);
alert(chart.datasets[0].points.indexOf(points[0]));
}
Managed to solve this eventually. Used the app.getComponent() method to get a reference to the ng2-chart object and then to the internal chart.js chart object.
HTML: (added the element id 'mylinechart')
<base-chart id="mylinechart" class="chart"
[data]="chartData"
[labels]="chartLabels"
[options]="lineChartOptions"
[colours]="lineChartColours"
[legend]="lineChartLegend"
[chartType]="chartType"
(chartClick)="chartClicked($event)"></base-chart>
Typescript:
constructor(private app: IonicApp) {
}
chartClicked(e: any) {
var chartComponent = this.app.getComponent('mylinechart'); //ng2-chart object
var chart = chartComponent.chart; //Internal chart.js chart object
console.log(chart.datasets[0].points.indexOf(e.activePoints[0]));
}
Update on 14-Feb-2017 with #ViewChild
If the above doesn't work (due to angular updates) try this. I didn't test this exact code as I don't have the exact source code anymore. In my current project I'm using angular 2.4 so I know #ViewChild works.
Change the HTML markup to:
<base-chart #mylinechart class="chart" etc.. (notice #mylinechart)
Type script:
At the top: import { Component, ViewChild } from '#angular/core';
And then inside your component class:
#ViewChild('mylinechart')
private chartComponent: any;
constructor(private app: IonicApp) {
}
chartClicked(e: any) {
var chart = this.chartComponent.chart; //Internal chart.js chart object
console.log(chart.datasets[0].points.indexOf(e.activePoints[0]));
}
Basically #ViewChild gets you a reference to the component marked by '#mylinechart' in the template. Decorating the chartComponent variable with #ViewChild makes it possible to access the chart component via that variable. Please note that references returned by #ViewChild are only available after 'ngAfterViewInit' life-cycle event. Since my use case is a chart 'click' event, I can safely assume that the view has been initialized by that time.
Reference: Angular #ViewChild
Related
Is there a way to provide data when setting the rootPage in Ionic 2? I know I can provide data with the NavController like so:
this.navCtrl.push(NewPage, {
foo: bar
})
but if I want to set a new rootPage, how can I pass data?
You can set root page and pass the data like below:
this.navCtrl.setRoot(YourPage,{myData:"test data"})
then you can get this data in 'YourPage' like below:
this.navParam.get('myData')
in app.component.ts I have the following:
export class MyApp {
#ViewChild(Nav) nav: Nav;
...
so I can change the rootPage like so:
this.nav.push(NewPage, {
foo: bar
})
rather than:
this.rootPage = NewPage;
and any data passed will be available in NewPage
Pop a page off of the navigation stack:
this.navCtrl.pop();
To change the root page at any point throughout the application:
this.navCtrl.setRoot(SecondPage);
Passing Data to root page:
this.navCtrl.push(SecondPage, {
thing1: data1,
thing2: data2
});
I have multiple charts showing different data. however they are all the same object type e.ge [acc1, acc2, acc3]. Therefore I was wondering if it is possible to have one parent legend set on a page somewhere and clicking it will show/hide all the corresponding dataset from all the charts?
I think you can hide all the legends of the charts except for one and implement a custom onClick function to handle clicks on that legend and hide all the corresponding datasets for each chart.
The current onClick implementation looks like this:
onClick: function(e, legendItem) {
var index = legendItem.datasetIndex;
var ci = this.chart;
var meta = ci.getDatasetMeta(index);
// See controller.isDatasetVisible comment
meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
// We hid a dataset ... rerender the chart
ci.update();
}
This function needs to be defined in options.legend.onClick. To make this work you would need to rewrite the above function to implement a loop, selecting all the charts necessary and select the meta, hide it and update the chart.
I have a component which is inserted into the DOM as a '' tag (e.g., default behaviour). The component's job is to wrap a 3rd party jQuery tool and I'm trying to ensure it is responsive to "resize" events so I would like to explicitly set width and height style attributes.
In the component, it is easy enough to being to the style attribute:
attributeBindings: ['style'],
style: function() {
return "width: auto";
}.property('widthCalc'),
In this case, this works but doesn't do anything useful because style just returns a static string (width: auto).
Instead what I want to do is -- based on any change to the computed property widthCalc -- set the width based on the new value. So here's the next logical step:
style: function() {
var width = $('body')[0].offsetWidth;
return 'width: ' + width + 'px';
}.property('widthCalc'),
This too works, dynamically setting the DIV to the width of the body's width (note: this isn't really what I want but it does prove that this simple binding works). Now what I really want is to get the value of width from a computed property on the component but I don't even have to go that far to run into trouble; notice that instead of a global jQuery selector I switch to a localised component-scoped selector:
style: function() {
var width = this.$().offsetWidth;
return 'width: ' + width + 'px';
}.property('widthCalc'),
Unfortunately this causes the page NOT to load and gives the following error:
Uncaught Error: Something you did caused a view to re-render after it rendered but before it was inserted into the DOM.
I imagine this is Ember run-loop juju but I'm not sure how to proceed. Any help would be appreciated.
Since it is not possible to call this.$() in the component before it has been added to the dom, provide an initial value until the component is ready.
For example,
Setting a default value to the property style and on didInsertElement event reopen the class and define style as a calculated property using this.$()
http://emberjs.jsbin.com/delexoqize/1/edit?html,js,output
js
App.MyCompComponent = Em.Component.extend({
attributeBindings:["style"],
style:"visibility:hidden",
prop1:null,
initializeThisStyle:function(){
this.set("style","visibility:visible");
this.reopen({
style:function(){
// var thisOffsetWidth = this.$().get(0).offsetWidth;
return "visibility:visible;color:red;background-color:lightgrey;width:"+this.get("prop1")+"px";
}.property("prop1")
});
}.on("didInsertElement")
});
Alternatively handle the error raised by this.$() and provide a default value. Afterwards when the component will be added the property will be calculated as planned.
http://emberjs.jsbin.com/hilalapoce/1/edit?html,js,output
js
App.MyCompComponent = Em.Component.extend({
attributeBindings:["style"],
style:function(){
try{
this.$();//this will throw an erro initialy
return "visibility:visible;color:red;background-color:lightgrey;width:"+this.get("prop1")+"px";
}catch(e){
return "color:blue";
}
}.property("prop1"),
prop1:null
});
With the component I was trying to solve for I ended coming up with an solution that seems effective to me which I will share below. For an understanding of the why I was getting the error and how one might more directly address that error please see the comment from #melc above.
My Solution
What I'm solving for is resizing a jQuery component wrapped in an Ember component. In many cases, resizing is handled gracefully by CSS alone but some jQuery components -- including the very nice knob component from aterrien -- has JS which gets directly involved and therefore needs the containers width and height properties to be set explicitly by the Ember component so that it reacts appropriately.
When solving for this I realised my use-case had two problems:
Solving for a page resize event
Adjusting to the fact that my knob component was -- at times -- in the DOM but in a part of the DOM which was not visible (more explicitly it was in Bootstrap tab which wasn't visible).
The Resize Listener
The first part of the solution is to listen for a page-level resize of the page. I do this with the following:
resizeListener: function() {
var self = this;
self.$(window).on('resize', Ember.run.bind(self, self.resizeDidHappen));
}.on('didInsertElement'),
Page Resize Handler
When a resize is done at the "page" level I now want my component to inspect what the resize impact has been on the component:
resizeDidHappen: function() {
Ember.run.debounce(this, function() {
// get dimensions
var newWidth = Number(this.$().parent().get(0).offsetWidth);
var newHeight = Number(this.$().parent().get(0).offsetHeight);
// set instance variables
this.set('width', newWidth);
this.set('height', newWidth);
// reconfigure knob
this.$('.knob').trigger(
'configure',
{
width: newWidth,
height: newWidth
}
);
}, 300);
}
This solves the page resize problem if it exists in isolation but to make the component it is probably a good idea to solve for the visibility use case as well (certainly in my case it was critical).
Visibility Handler
Why? Well, for two reasons that I can think of:
Many jQuery components refuse to load or perform badly if they aren't loaded
The ember component appears to not be able to establish a "resize" event when it is not visible in the DOM
The one problem is that there is no DOM-level event for visibility changes, so how do we react to a change in visibility without polling on an interval? Well in most cases there will be a UI element which is controlling the state of visibility. In my case it's Bootstrap's tab bar and in this case they have events that fire on the tabs when they become visible. Great. Here's a selector for Bootstrap's selector (assuming you're inside the content area of the newly visible tab):
visibilityEventEmitter: function(context) {
// since there is no specific DOM event for a change in visibility we must rely on
// whatever component is creating this change to notify us via a bespoke event
// this function is setup for a Bootstrap tab pane; for other event emmitters you will have to build your own
try {
var thisTabPane = context.$().closest('.tab-pane').attr('id');
var $emitter = context.$().closest('.tab-content').siblings('[role=tabpanel]').find('li a[aria-controls=' + thisTabPane + ']');
return $emitter;
} catch(e) {
console.log('Problem getting event emitter: %o', e);
}
return false;
},
visibilityEventName: 'shown.bs.tab',
then we just need to add the following code:
_init: function() {
var isVisible = this.$().get(0).offsetWidth > 0;
if (isVisible) {
this.visibilityDidHappen();
}
}.on('didInsertElement'),
visibilityListener: function() {
// Listen for visibility event and signal a resize when it happens
// note: this listener is placed on a DOM element which is assumed
// to always be visibile so no need to wait on placing this listener
var self = this;
Ember.run.schedule('afterRender', function() {
var $selector = self.get('visibilityEventEmitter')(self);
$selector.on(self.get('visibilityEventName'), Ember.run.bind(self, self.visibilityDidHappen ));
});
}.on('didInsertElement'),
visibilityDidHappen: function() {
// On the first visibility event, the component must be initialised
if(!this.get('isInitialised')) {
this.initiateKnob();
} else {
// force a resize assessment as window sizing may have changed
// since last time component was visible
this.resizeDidHappen();
}
},
Note that this also results in a tiny refactor of our resize listener, removing it's trigger from the didInsertElement event and instead being triggered by initiateKnob which will happen not when the Ember component loads but instead lazy load at the first point of visibility in the DOM.
initiateKnob: function() {
var self = this;
this.set('isInitialised', true);
var options = this.buildOptions();
this.$('.knob').knob(options);
this.syncValue();
this.resizeDidHappen(); // get dimensions initialised on load
console.log('setting resize listener for %s', self.elementId);
self.resizeListener(); // add a listener for future resize events
},
resizeListener: function() {
this.$(window).on('resize', Ember.run.bind(this, this.resizeDidHappen));
},
Does it work?
To a large degree but not completely. Here's what works:
the first 'tab' which is visible at load resizes on demand
all tabs resize when they are switched to (aka, when they gain visibility)
what doesn't work is:
tabs other than the first tab do not resize (aka, the onresize callback appears broken)
The error I get is:
vendor.js:13693 Uncaught TypeError: undefined is not a function
Backburner.run vendor.js:13716
Backburner.join vendor.js:34296
run.join vendor.js:34349
run.bind vendor.js:4759
jQuery.event.dispatch vendor.js:4427
jQuery.event.add.elemData.handle
Not sure what to make of this ... any help would be appreciated. Full code can be found here:
https://gist.github.com/295e7e05c3f2ec92fb45.git
I need inser data from model to dataTables "aaData:". I can't get objects from store at normal array, but as DS.RecordArray and what next? Console command to get some properties of some object is following command :
var dev = App.Model.Store.find("model")
dev.content.content[1]._data.someProperty
I don't know how to get this object or his property at javascript.
Please, help :)
With Ember Data beta 1 or later you'd do this in a controller or route.
var dev = this.store.find("model");
// dev is a promise that will be resolved when/if
// the collection is actually loaded
dev.then(function(realDev){
// at this point realDev is a DS.RecordArray
// you could turn it into a real array by cally .toArray()
var devAry = realDev.toArray();
// then you can call get() on an item to retrieve a property
var someProp = devAry[1].get('someProperty');
});
I know how to update and redraw a jqPlot object without using ember...
I created the following fiddle to show the "problem": http://jsfiddle.net/QNGWU/
Here, the function load() of App.graphStateController is called every second and updates the series data in the controller's content.
First problem: The updates of the series seem not to propagate to the view.
Second problem: Even if they would, where can i place a call to update the plot (i.e. plotObj.drawSeries())?
I already tried to register an observer in the view's didInsertElement function:
didInsertElement : function() {
var me = this;
me._super();
me.plotObj = $.jqplot('theegraph', this.series, this.options);
me.plotObj.draw();
me.addObserver('series', me.seriesChanged);
},
seriesChanged: function() {
var me = this;
if (me.plotObj != null) {
me.plotObj.drawSeries({});
}
}
But that didn't work...
Well, figured it out, see updated fiddle.
The secret sauce was to update the whole graphState object (not just it's properties) in App.graphStateController:
var newState = App.GraphState.create();
newState.set('series', series);
me.set('content', newState);
And then attach an observer to it in the App.graphStateView:
updateGraph : function() {
[...]
}.observes('graphState')
The updateGraph function then isn't pretty, since jqPlot's data series are stored as [x,y] pairs.
The whole problem, i guess, was that the properties series and options in the App.graphState object itself are not derived from Ember.object and therefore no events are fired for them. Another solution may be to change that to Ember.objects, too.