2016-08-02 74 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得到解决,没有多少可替代的。