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

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


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);    }}


Use ElementRef

ElementRef will inject the current DOM node into your component. The ElementRef service will always be local to your current DOM node.

Having injected it, you can get hold of the actual DOM node using nativeElement:

var el = elementRef.nativeElement

Once you have this, you can manipulate it it in any way you like, either using DOM scripting, or using a DOM wrapper like jQuery:

$(el)  .append('<p>Some interesting Stuff')  .addClass('my_class');

But don't do this if you can help it

Be aware that, as with Angular 1, the use of direct DOM manipulation is discouraged. You can get pretty much all of your work done using templates, and you should favour this way of working most of the time.

Direct DOM manipulation leads to convoluted, hard to understand, hard to test code.

There are times though, when it can seem like the best solution. For example, if you have to integrate with a third party, high-complexity framework like a graphing library.

Here's a worked example (in ES6)

var AppComponent = ng.core  .Component({    selector: "app",    template:    `      <div>Captured element</div>    `  })  .Class({    constructor: [ng.core.ElementRef, function(elementRef) {      var el = elementRef.nativeElement      el;    }]  })


Note: [Deprecated]

You can use "BrowserDomAdapter"
https://angular.io/docs/ts/latest/api/platform/browser/BrowserDomAdapter-class.html

import {BrowserDomAdapter} from 'angular2/platform/browser'@Component({  selector: 'dom',  templateUrl: 'path/to/template.html',  providers: [BrowserDomAdapter]})export class DomComponent {  constructor(private _dom: BrowserDomAdapter) {    var domIWant = this._dom.query('whatever you want to get');  }}

Process

  1. import BrowserDomAdapter
  2. apply providers: [BrowserDomAdapter]
  3. initiate in constructor()
  4. get dom using instanced BrowserDomAdapter