Angular: Using ComponentFactoryResolver for dynamic instantiation of the components, rendering inside SVG

前端 未结 3 1537
有刺的猬
有刺的猬 2020-12-31 15:19

I have a component, which renders DOM, which is expected to be inside svg tag:

import { Component, Input          


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 15:44

    I assume there are two questions here:

    1. How to make it work?
    2. Why is that happening?

    The answer to the first question is using svg instead of g for grouping elements.
    In your concrete example it would mean changing the selector:

    @Component({
      selector: 'svg[hello]',
      template: `Hello, {{name}}`,
      styles: [`h1 { font-family: Lato; }`]
    })
    

    And app.component.html:

    
      
    
    
    • Working StackBlitz
    • Nested svg vs group

    Now let's get to the second question. Why is this happening?
    Your selector doesn't contain svg namespace. In order to render it correctly the selector should be svg:g[hello].
    But that is impossible due to an old issue that's been there since Angular 5.
    More details here and here.

    As mentioned in this comment the main issue here is that Angular selector cannot contain namespace for creating element.
    Selector svg:g[hello] will be parsed to g[hello], as a result Angular will use document.createElement instead of document.createElementNS to create new element.

    Why using svg[hello] works?
    Because if we use selector svg[hello] then it is parsed to and for this tag Angular is providing namespace implicitly:

    'svg': new HtmlTagDefinition({implicitNamespacePrefix: 'svg'}),
    

提交回复
热议问题