2016-08-02 75 views
3

我正在創建一個使用SVG的Web應用程序。 我創建了包含SVG元素的組件,並將它們放入根元素svg中。 他們有屬性選擇器,因爲SVG/XML文檔樹是嚴格的,所以我不能使用元素選擇器。 他們有一個模板,svg:g標記開頭:如何在Angular2中動態創建SVG組件?

@Component({ 
    selector:'[foo]', 
    template: '<svg:g>...</svg:g>', 
}) 

在應用程序中,我想創建一個組件時,用戶按下一個按鈕, 並同時開始拖動。 我認爲這可以通過建立動態使用ComponentResolver的組件來實現:

@ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef}) 
    protected dynamicComponentTarget: ViewContainerRef 

    private componentResolver: ComponentResolver 

    onMouseDown() { 
    this.componentResolver 
     .resolveComponent(FooComponent) 
     .then((factory) => { 
     const dynamicComponent = this.dynamicComponentTarget.createComponent(factory, 0) 
     const component: FooComponent = dynamicComponent.instance 
     const element = dynamicComponent.location.nativeElement 
     // add event listener to start dragging `element`. 
     }) 
    } 

組件時調用onMouseDown()被創建,但它的DOM元素是div,所以它是SVG文件非法元素,不能被顯示。

我試圖與selector='svg:g[foo]',創建然後g元件,但它的命名空間不爲SVG(http://www.w3.org/2000/svg),但正常的HTML命名空間(http://www.w3.org/1999/xhtml)和它的類是HTMLUnknownElement>g

我也試過用selector='svg:svg[foo]',然後svg:svg元素被創建並顯示出來。但svg:svg不能與transform屬性一起移動,所以這對我的應用程序不起作用。

如何爲屬性選擇器組件動態創建svg:g元素?

我正在使用Angular2:2.0.0-rc4。

+0

聽起來像https:// github。com/angular/angular/issues/10404 –

+0

謝謝,@GünterZöchbauer!這個問題與我想嘗試的相同。感謝您的信息。我正在等待解決方案/錯誤修復。 – tyfkda

回答

0

而不是嘗試使用Component Resolver創建組件到視圖中,而是使用Component Resolver來代替。

  • 創建一個對象,其屬性與要傳遞給SVG組件的屬性相匹配。
  • 將此對象附加到數組(ex.svgItems)。
  • 將* ngFor =「svgItems」添加到要動態創建的SVG組件中。

希望它是明確的,並解決您的問題。

2

對於將g元素渲染爲svg的命名空間問題,您是對的。不幸的是,將節點作爲svg元素附加是正確地將組件命名爲命名空間的唯一方法。

但是,這並不意味着這不起作用。如果將拖放功能添加爲模板中g元素的指令,則它將與您的組件一起編譯,並且可以將邏輯偏移到該指令中。頂級svg將正確命名空間,並且模板將相應地繼承此名稱。

import {Component, Input} from '@angular/core'; 

@Component({ 
    selector: 'svg:svg[customName]', // prevent this from hijacking other svg 
    template: '<svg:g dragDirective>...</svg:g>', // note the directive added here 
    style: [] 
}) 
export class GComponent { 

    constructor() { } 

} 

這可能不是很理想,但直到https://github.com/angular/angular/issues/10404得到解決,沒有多少可替代的。