簡體   English   中英

我執行d3JS追加時未調用Angular2組件

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

我的d3JS和Angular2組件有問題。

我想將我的角度分量用於d3生成的代碼。

例如,我有根角度分量:

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

我有孩子指令

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

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

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

不幸的是,我沒有看到控制台日志,但是在DOM中,我擁有該元素

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

為什么angular2不響應我的元素? 以及我該如何解決?

Angular不會為動態添加的HTML創建組件或指令。 與組件或指令選擇器匹配的HTML必須靜態添加到父組件模板。

要動態添加組件,可以使用ViewContainerRef.createComponent()

有關具體示例,請參見帶有用戶單擊所選組件的Angular 2動態選項卡

在這種特殊情況下,我將使用以下內容:

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

  public ngOnInit() {
  }
}

否則,該指令將不會被應用...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM