The gist captures my approch forcreating an angular component for Datamap. I did'nt want to include d3 or topojson in my angular.json file or the index.html file since doing so would import them during initial page load which is redundant for me.
The other approches i tried involved importing d3, topojson and datamap in my component file, the problem that i faced with that approch is
- d3 and topojson imports were getting ignored (i guess this should be the work of angular compilere since i am not refereing them in my component).
- Datamap din't really have a very ts compatible index files
So finally i created a service that would import d3, topojson and datamap, inject the service into the component. In the ngOnInit method get the instance of d3 and topojson and assign them to window window and initialise the datamap. This would creat datamap on the browser. Once datamap is created unset d3 and topojson from the window scope.
You can use the following steps to create a data map component in angular
npm install d3 --save
npm install topojson --save
npm i datamaps --save
--------------------------------datamap-world.component.ts--------------------------------
import { Component, OnInit } from '@angular/core';
import {D3Service} from "./d3.service";
@Component({
selector: '<datamap-world>',
template: '<div id="container" style="position: relative; width: 1000px; height: 400px;"></div>'
})
export class DatamapWorldComponent implements OnInit {
map: any;
constructor(private d3service: D3Service) { }
ngOnInit() {
this.map = this.createMap();
}
private createMap() {
window['d3'] = this.d3service.getD3();
window['topojson'] = this.d3service.getTopo();
let dataMap: Function = this.d3service.getDataMap();
const map = new dataMap({element: document.getElementById('container')});
delete window['d3'];
delete window['topojson'];
return map;
}
}
-----------------------------------------d3.service.ts------------------------------------
import { Injectable } from '@angular/core';
import * as d3 from 'd3';
import * as topojson from 'topojson';
import * as Datamap from 'datamaps/dist/datamaps.world'
export type D3 = typeof d3;
export type Topojson = typeof topojson;
export type Datamap = typeof Datamap;
@Injectable()
export class D3Service {
constructor() { }
public getD3(): D3 {
return d3;
}
public getTopo(): Topojson {
return topojson;
}
public getDataMap(): Function {
return Datamap;
}
}