简体   繁体   中英

Angular2 component not called when I do d3JS append

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?

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM