我有一个json结构,它指示一个富文本,我使用angulars渲染器创建并将其直接添加到dom中,如下所示:
@Component({
selector: 'formatted-text',
templateUrl: 'formatted-text.component.html'
})
export class FormattedTextComponent implements OnInit {
nativeElement: Node;
constructor(private renderer: Renderer,
private elementRef: ElementRef,
private resolver: ComponentFactoryResolver,
private viewContainerRef: ViewContainerRef) {
this.nativeElement = elementRef.nativeElement;
}
private renderPart(part, parent) {
if ('plain' == part.tag) {
this.renderer.createText(parent, part.content);
}
else {
if (part.content instanceof Array) {
let nativeElement = this.renderer.createElement(parent, part.tag);
for (let e of part.content) {
this.renderPart(e, nativeElement);
}
}
else if (typeof part.content == "object") {
if (part.tag == 'include') {
this.addElement(part.content);
}
else {
let nativeElement = this.renderer.createElement(parent, part.tag);
this.renderPart(part.content, nativeElement);
}
}
else {
let nativeElement = this.renderer.createElement(parent, part.tag);
this.renderer.setText(nativeElement, part.content);
}
}
}
JSON-Structure看起来像这样:
[
{
"tag": "b",
"content": "Hello World, "
},
{
"tag": "include",
"content": {
"className": "link-internal",
"element": {
"link": "/test/en-US",
"text": "Click Here",
"target": "_blank",
"follow": true
}
}
},
{
"tag": "plain",
"content": "This is plain text "
},
{
"tag": "table",
"content": {
"tag": "tr",
"content": [
{
"tag": "td",
"content": "table cell"
},
{
"tag": "td",
"content": "table cell 2"
}
]
}
},
{
"tag": "u",
"content": {
"tag": "i",
"content": "multiple formats are possible"
}
}
]
创建格式化文本,就像这样工作。我的问题是,包括组件。正如您在JSON-Structure中所看到的,我希望包含一个名为" internal-link"的组件。它呈现链接等。由于元素没有自己的视图,我不知道如何向它们添加组件。
我的想法是为纯文本等创建一个组件,然后将这些组件堆叠在一起。这似乎是很多组件,仅用于格式化文本。
如果有人知道如何正确地做到这一点,我会很感激。
提前致谢