简体   繁体   English

我执行d3JS追加时未调用Angular2组件

[英]Angular2 component not called when I do d3JS append

I have a problem with d3JS and Angular2 component. 我的d3JS和Angular2组件有问题。

I want to use my angular components for code which was generated by d3. 我想将我的角度分量用于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 不幸的是,我没有看到控制台日志,但是在DOM中,我拥有该元素

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

Why angular2 does not respond to my elements? 为什么angular2不响应我的元素? And how I can fix it? 以及我该如何解决?

Angular doesn't create components or directives for HTML that is added dynamically. Angular不会为动态添加的HTML创建组件或指令。 The HTML that matches the components or directives selectors has to be statically added to the parent components template. 与组件或指令选择器匹配的HTML必须静态添加到父组件模板。

To add components dynamically you can use ViewContainerRef.createComponent() 要动态添加组件,可以使用ViewContainerRef.createComponent()

For a concrete example see Angular 2 dynamic tabs with user-click chosen components 有关具体示例,请参见带有用户单击所选组件的Angular 2动态选项卡

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... 否则,该指令将不会被应用...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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