score:3

i was having trouble using elementref, i'm not sure if that api has changed. so i ended up using viewcontainref to get the nativeelement.

import {component, viewcontainerref, oninit} from '@angular/core';
declare var d3:any;
@component({
    selector: 'line-chart',
    directives: [],
    template: `<div class="sh-chart">chart</div>`
})
export class linechart implements oninit{
    elem ;
    constructor(private viewcontainerref:viewcontainerref) {}
    ngoninit(){
        this.elem = this.viewcontainerref.element.nativeelement;

        d3.select(this.elem).select("div").style("background-color", "yellow");
    };
}

score:4

npm install --save d3

check d3 version in package.json and check it in node_modules too.

then, in the component.ts, import it as below

import * as d3 from 'd3';

score:6

try this:

npm install d3@3.5.36 --save to set the version you need

npm install @types/d3@3.5.36 --save or a higher version if you want d3 4+

and then in your ts do

import * as d3 from 'd3';

should work just fine

score:58

to use renderer, you need the raw html element (aka nativeelement). so basically you have to use whatever your library is, get the raw element and pass it to renderer.

for example

// h3[0][0] contains the raw element
var h3 = d3.select(this.el.nativeelement).select('h3');
this.renderer.setelementstyle(h3[0][0], 'background-color', 'blue');

the warning about elementref is about using it directly. that means that this is discouraged

elementref.nativeelement.style.backgroundcolor = 'blue';

but this is fine

renderer.setelementstyle(elementref.nativeelement, 'background-color', 'blue');

for showing purposes you can use it as well with jquery

// h2[0] contains the raw element
var h2 = jquery(this.el.nativeelement).find('h2');
this.renderer.setelementstyle(h2[0], 'background-color', 'blue');

my recommendation though is to stick to use what angular2 provides you to do this easily without depending on another libraries.

with pure angular2 you have two easy ways

  • using directives
// this directive would style all the h3 elements inside mycomp
@directive({
    selector : 'h3',
    host : {
        '[style.background-color]' : "'blue'"
    }
})
class h3 {}

@component({
    selector : 'my-comp',
    template : '<h3>some text</h3>',
    directives : [h3]
})
class mycomp {}
  • using viewchild with local variables
@component({
    selector : 'my-comp',
    template : '<h3 #myh3>some text</h3>',
})
class mycomp {
    @viewchild('myh3') myh3;
    ngafterviewinit() {
        this.renderer.setelementstyle(this.myh3.nativeelement, 'background-color', 'blue');
    }
}

here's a plnkr with all the cases i mentioned in this answer. your requirements may differ, of course, but try to use angular2 whenever you can.


Related Query

More Query from same tag