0

I have a problem with d3JS and Angular2 component.

I want to use my angular components for code which was generated by d3.

For example I have root angular compoennt:

import { Component, OnInit } from '@angular/core';
import { ChildDirective } from './child.directive';
import * as d3 from 'd3';

@Component({
  selector: 'root',
  template: `<svg></svg>`,
  directives: [ ChildDirective ],
})

export class rootComponent implements OnInit {

  constructor(private el: ElementRef) {
  }

  public ngOnInit() {
    d3.select(this.el.nativeElement).selectAll('svg').append('g').attr('child', '');
  }
}

And I have child directive

import { Directive } from '@angular/core';

@Directive({
  selector: '[child]'
})

export class ChildDirective {
  constructor() {
    console.log('I"m alive! Hello world!');
  }
}

And unfortunately I don't see my console log, but in DOM I have that elements

<svg _ngcontent-vja-4="" class="calendar">
  <g child=""></g>
</svg>

Why angular2 does not respond to my elements? And how I can fix it?

Eugene Kubesh
  • 185
  • 1
  • 2
  • 14

2 Answers2

0

Angular doesn't create components or directives for HTML that is added dynamically. The HTML that matches the components or directives selectors has to be statically added to the parent components template.

To add components dynamically you can use ViewContainerRef.createComponent()

For a concrete example see Angular 2 dynamic tabs with user-click chosen components

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

I would use the following in this particular case:

@Component({
  selector: 'root',
  template: `
    <svg>
      <g child></g>
    </svg>
  `,
  directives: [ ChildDirective ],
})
export class rootComponent implements OnInit {
  constructor(private el: ElementRef) {
  }

  public ngOnInit() {
  }
}

Otherwise the directive won't be applied...

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360