【发布时间】:2019-11-11 10:47:56
【问题描述】:
我有一个渲染DOM的组件,预计在svg标签内:
import { Component, Input } from '@angular/core';
@Component({
selector: 'g[hello]',
template: `<svg:text x="50%" y="50%" text-anchor="middle">Hello, {{name}}</svg:text>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
}
当我静态实例化它时,一切正常(文本在页面上可见):
<svg>
<svg:g hello name="Static component"></svg:g>
</svg>
生成以下 DOM:
<svg _ngcontent-iej-c129="">
<g _ngcontent-iej-c129="" hello="" name="Static component" _nghost-iej-c130="" ng-reflect-name="Static component">
<text _ngcontent-iej-c130="" text-anchor="middle" x="50%" y="50%">
Hello, Static component
</text>
</g>
</svg>
当我尝试使用 ComponentFactoryResolver 动态实例化组件时,问题就开始了:
<svg>
<ng-container #container></ng-container>
</svg>
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, OnInit } from '@angular/core';
import { HelloComponent } from './hello.component'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
@ViewChild('container', {read: ViewContainerRef, static: true}) container: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit() {
// Instantiating HelloComponent dynamically
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent)
const componentRef = this.container.createComponent(componentFactory);
componentRef.instance.name = 'Dynamic component'
}
}
生成的 DOM 看起来不错,但由于某种原因,页面上看不到文本:
<svg _ngcontent-iej-c129="">
<!---->
<g hello="" _nghost-iej-c130="">
<text _ngcontent-iej-c130="" text-anchor="middle" x="50%" y="50%">
Hello, Dynamic component
</text>
</g>
</svg>
【问题讨论】: