如何在Angular2中动态创建SVG组件?
我正在创建一个使用SVG的Web应用程序.
我创建了由SVG元素组成的组件,并将它们放入根svg元素中. 它们有属性选择器,因为SVG / XML文档树是严格的所以我不能使用元素选择器. 他们有一个模板以svg:g标签开头: @Component({ selector:'[foo]',template: '<svg:g>...</svg:g>',}) 在应用程序中,我想在用户按下按钮时创建一个组件, @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. 解决方法
对于保持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解决之前,没有太多选择. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |