So I'm using d3.js with typescript and angular2, and I'm trying to extend the prototype property of selections in ngOnInit() like:
import { Component, Input, Injectable } from '@angular/core';
import { Http, HTTP_BINDINGS, Response } from '@angular/http';
import { bootstrap } from 'angular2/platform/browser';
import { RouteParams } from '@angular/router-deprecated';
import { Router } from '@angular/router-deprecated';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';
import * as d3 from 'd3';
import { DataService } from './data.service';
@Component({
selector: 'measure',
templateUrl: 'app/new-container.html',
styleUrls: ['app/new-container.css']
})
export class NewContainer {
public measures;
public dimensions;
public dimensionsAlias;
public id: string;
constructor(private router: Router, private routeParams: RouteParams, private _dataService: DataService) {}
ngOnInit() {
if (this.routeParams.get('id') != null) {
this.id = this.routeParams.get('id');
}
/* deleting previous svg canvas to make room for the new one */
var s = d3.selectAll('svg');
s.remove();
d3.selection.prototype.moveToFront = function() {
return this.each(function(){
this.parentNode.appendChild(this);
});
}
d3.selection.prototype.moveToBack = function() {
return this.each(function() {
var firstChild = this.parentNode.firstChild;
if( firstChild ) {
this.parentNode.insertBefore(this, firstChild);
}
});
}
this.getAll();
}
/* gets data from json files */
getAll() {
this._dataService.getAll().subscribe(
data => {
this.measures = data[0];
this.dimensions = data[1];
this.dimensionsAlias = data[2];
},
err => {
console.error(err);
},
() => {
/* this is where I draw everything and use the moveToFront
and moveToBack properties on selections */
this.draw();
}
);
}
The problem is that typescript is throwing an error saying:
error TS2339: Property 'moveToFront' does not exist on type 'Selection<any>'.
error TS2339: Property 'moveToBack' does not exist on type 'Selection<any>'.
These errors are being thrown, but extending the prototype successfully adds the moveToFront and moveToBack properties to selections since doing something like:
d3.select("#container").moveToFront();
works and moves that element to the front. So it works, but an error is still being thrown where I extended the prototype and every time I call moveToFront as well.
Does anyone know how to fix this error? Thanks.