Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Component - Access DOM (or create Component without template, purely from JS)

Tags:

Trying to play with Angular 2 here... understood that it's still in alpha.

How do I access DOM elements from Component? Specifically, I would like to use other libraries like d3 to generate custom DOM from code. I suppose I need to create a component and somehow plug into component life-circle to alter DOM with d3... any idea where to start digging?

I'm using this quickstart repo.

Thanks!

like image 705
Anatoly Avatar asked May 05 '15 17:05

Anatoly


1 Answers

If you don't mind using Directive instead of Component it is straightforward. For Angular 2.0.0-alpha.33 in typescript you can use D3 to manipulate the DOM by Injecting an ElementRef:

@Directive({     selector:   'scatter-plot',     lifecycle: [LifecycleEvent.onChange],     properties: [ 'data' ] }) export class ScatterPlot {      root: Selection<any>;     data: Array<ScatterPlotDataPoint>;      x: (number) => number;     y: (number) => number;      defaultSize: string;     circles: any;      constructor(         @Inject(ElementRef) elementRef: ElementRef,         @Attribute('height') height: string,         @Attribute('default-size') defaultSize: string     ) {         var el:HTMLElement = elementRef.nativeElement;         this.root = d3.select(el);          this.defaultSize = defaultSize ? defaultSize : "5";         this.circles = this.root             .append('svg')             .attr('class', 'chart')             .style({                 'width':  '100%',                 'height': height ? height + 'px': '',             }).             selectAll('circle');      }      render(newValue) {         if (!newValue) return;          this.x = d3.scale.linear().domain([-10, 110]).range([0, 250]);         this.y = d3.scale.linear().domain([-10, 110]).range([100, 0]);          this.circles = this.circles             .data(newValue);          this.circles.exit().remove();          this.circles.enter()             .append('circle');          this.circles             .transition()             .attr("r", d => d.size ? d.size: this.defaultSize)             .style("fill", d => d.color)             .attr('cx', d => this.x(d.x))             .attr('cy', d => this.y(d.y));      }      onChange() {         this.render(this.data);     } } 
like image 168
Hardbyte Avatar answered Sep 23 '22 07:09

Hardbyte