【发布时间】:2017-06-11 22:11:45
【问题描述】:
在 Angular2 中,有没有办法通过选择器调用组件,而该选择器不会出现在 DOM 中?
我的问题是我想用 Angular2 制作一个带有 SVG 渲染的游戏。我有一个匹配组件(我的主要匹配容器),它调用一个字段组件(绘制字段)。我的匹配组件是 SVG 元素,字段是 SVG Rect 元素。
这是我的比赛组件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'match',
template: `
<svg:svg width="800" height="600" style="background-color:purple;">
<field></field>
</svg:svg>
`
})
export class MatchComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
}
还有我的字段组件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'field',
template: `
<svg:rect width="600" height="300" fill="yellow"></svg:rect>
`
})
export class TerrainComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
}
当我启动我的解决方案时,它正在工作,但 SVG 不像我想要的那样,因为 DOM 中有一个元素破坏了 SVG:
<match>
<svg height="600" style="background-color:purple;" width="800">
<field>
<rect fill="yellow" height="300" width="600"></rect>
</field>
</svg>
</match>
你知道是否可以在结果 DOM 中使用选择器吗?或者有没有更好的方法来使用 Angular 2 生成 SVG?
编辑:我找到了一个使用 SVG 组的解决方案,但我认为这不是最好的解决方案,我宁愿在 DOM 中根本没有选择器标记。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'match',
template: `
<svg:svg width="800" height="600" style="background-color:purple;">
<g field></g>
</svg:svg>
`
})
export class MatchComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
}
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'g[field]',
template: `
<svg:rect width="600" height="300" fill="yellow"></svg:rect>
`
})
export class TerrainComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
}
它正在渲染这个 SVG,谁在工作:
<match>
<svg height="600" style="background-color:purple;" width="800">
<g field="">
<rect fill="yellow" height="300" width="600"></rect>
</g>
</svg>
</match>
【问题讨论】:
-
有关信息,我已经阅读了这个问题和这个答案,但我不能应用相同的解决方案stackoverflow.com/questions/38287224/…
-
我也一直在尝试找出框架是否可以做到这一点。如果您遇到答案,请让大家知道。