Angular 动态组件加载 [英] Angular dynamic component loading
问题描述
我正在学习 Angular,我有一个带有 API 的 CMS,可以返回页面内容.页面可以有表单的短代码,我更新了 API 以用组件选择器替换短代码
示例页面内容如下
bla bla bla <app-form [id]="1"></app-form>在 angular 中,我创建了 FormComponent 来相应地加载表单,但是当我使用上述选择器获取页面内容时,我收到错误
'app-form' 不是已知元素:.....
我做了一些研究,发现我需要一些动态组件加载器,但找不到任何符合我的情况的工作示例,任何人都可以帮助我解决这个问题
解决方案 实际上,您必须动态创建这些组件.有关执行此操作的示例代码,请参阅此 plunkr:https://plnkr.co/edit/kkM1aR4yPcIqeBhamoDW?p=信息
尽管您需要一个用于 Angular 的 ViewContainer 才能知道在哪里插入该动态组件.这是行不通的,因为您无法绑定到 innerHTML
然后手动更改 innerHTML
的代码.我不确定,但我认为这会影响角度变化检测.
几个月前我不得不这样做并想出了一个解决方案.在这一点上我想提一下,我不确定现在是否有更好的解决方案来解决这个问题.无论如何,我所做的不是创建动态组件,而是使用 *ngIfs 创建一些自定义渲染.让我解释一下:您的内容包含标签.您决定这些标签的外观.在我的例子中,我有一个标签,用户可以在他想要的任何地方插入:[galerie="key_of_gallery"]
.所以内容可能看起来像
一些普通文本<h2>哦,多么好的标题</h2>[画廊="summer_gallery"]再发短信
现在我该如何渲染它?我必须得到类似的东西
一些普通文本<h2>哦,多么好的标题</h2><galerie [key]="summer_gallery"></galerie><div>再发短信
所以我创建了一个自定义组件来创建这个:
import { Component, Input } from '@angular/core';@成分({选择器:'ffam-render-key-value',模板:`<div *ngFor="let contentToRender of contentArray"><div *ngIf="contentToRender.type==='normal'" [innerHTML]="contentToRender.value">
<galerie *ngIf="contentToRender.type==='gallery'" [key]="contentToRender.key"></galerie>
`})导出类 NoeRenderKeyValueComponent{@Input('contentArray') contentArray: any[] = [];}
这个组件所需要的只是一个标签数组,这些标签将使用 *ngFor 进行渲染.根据标签的类型创建普通 HTML 或组件.
这个组件可以像
一样插入 </ffam-render-key-value>
为了获得这个标签数组,我创建了一个带有函数的服务:
public getArrayWithCustomTags(keyValue): any[] {让 arrayWithCustomTags: any[] = [];//检查innerHTML中是否存在自定义标签if (keyValue.value.indexOf('[galerie=') !== -1) {//替换双引号keyValue.value = keyValue.value.replace(/"/g, '"');//它存在,获取所有标签的数组//匹配所有 [galerie="SOME KEY"] 或 [someAttribute="some text here"] 的正则表达式 ->您必须更改此正则表达式以适合您的所有标签让模式 =/(?:(\[galerie=\"[^\"]+\"\]))+/;//用正则表达式拆分得到数组让 arrayOfContents: string[] = keyValue.value.split(new RegExp(pattern, 'gi'));for (let i = 0; i
这将创建一个数组,如:
[0]: {type: "normal", value:"SecureHTML"},[1]: {type: "gallery", key:"summer_gallery"},[2]: {type: "normal", value:"SecureHTML"},
好吧,我想你明白了.如果您创建一个带有更多标签的整个 CMS,我建议您创建一个函数,该函数可以轻松地为标签创建整个过程(正则表达式等).此示例代码仅适用于一个标签.
结果是组件就在用户放置它们的地方呈现.我希望这对您有所帮助.
顺便说一句,如果您有可编辑的用户键值对,您可能会发现这很有帮助:https://github.com/bergben/ng2-ck-editable.这是我构建的一个小模块,用于使用 ck-editor 使任何 div 可编辑.
I am learning Angular, I have a CMS with API that returns contents of pages. pages can have short codes for forms, I have updated the API to replace short with a component selector
Sample page contents would look like
<div>bla bla bla </div>
<app-form [id]="1"></app-form>
In angular I have created FormComponent to load form accordingly, but when I get page contents with above mentioned selector I get the error
'app-form' is not a known element:.....
I did some research and found that I need some dynamic component loader but could not found any working examples as per my scenario, can any one help on how I can fix this issue
Indeed you would have to create those components dynamically. See this plunkr for an example code to do that: https://plnkr.co/edit/kkM1aR4yPcIqeBhamoDW?p=info
Although you need a ViewContainer for Angular to know where to insert that dynamic component. Which would not work because you can't bind to innerHTML
and then change the code of the innerHTML
manually. I am not sure but I think that would mess with angulars change detection.
I had to do this a few months ago and came up with a solution. I want to mention at this point that I am not sure if there is a better solution to this problem by now. Anyway, what I did is not to create dynamic components but rather create some custom rendering with *ngIfs.
Let me explain: Your content contains tags. You decide how those tags look like.
In my case I had a tag that the user can insert wherever he wants: [galerie="key_of_gallery"]
.
So the content could look like
some normal text
<h2>Oh what a nice heading</h2>
[galerie="summer_gallery"]
text again
Now how can I render this? I would have to get something like
<div>
some normal text
<h2>Oh what a nice heading</h2>
</div>
<galerie [key]="summer_gallery"></galerie>
<div>
text again
</div>
So I created a custom component which creates this:
import { Component, Input } from '@angular/core';
@Component({
selector: 'ffam-render-key-value',
template: `<div *ngFor="let contentToRender of contentArray">
<div *ngIf="contentToRender.type==='normal'" [innerHTML]="contentToRender.value">
</div>
<galerie *ngIf="contentToRender.type==='gallery'" [key]="contentToRender.key"></galerie>
</div>`
})
export class NoeRenderKeyValueComponent{
@Input('contentArray') contentArray: any[] = [];
}
All this component needs is an array of tags which will be rendered with an *ngFor. Depending on the type of the tag either normal HTML or a component is created.
This component can be inserted like
<ffam-render-key-value [contentArray]="keyValues['_text'].arrayWithCustomTags">
</ffam-render-key-value>
To get this array of tags I have created a service with a function:
public getArrayWithCustomTags(keyValue): any[] {
let arrayWithCustomTags: any[] = [];
//check if custom Tag exists in the innerHTML
if (keyValue.value.indexOf('[galerie=') !== -1) {
//replace double quotes
keyValue.value = keyValue.value.replace(/"/g, '"');
//it exists, get array of all tags
//regex that matches all [galerie="SOME KEY"] or [someAttribute="some text here"] -> You have to change this regex to fit all your tags
let pattern = /(?:(\[galerie=\"[^\"]+\"\]))+/;
//split with regexp to get array
let arrayOfContents: string[] = keyValue.value.split(new RegExp(pattern, 'gi'));
for (let i = 0; i < arrayOfContents.length; i++) {
if (typeof arrayOfContents[i] === "undefined") {
arrayOfContents.splice(i, 1);
i--;
}
else {
let customTagToBeInserted: any = {};
if (arrayOfContents[i].indexOf('[galerie=') !== -1) {
//custom tag gallery
customTagToBeInserted.type = "gallery";
//get key only
customTagToBeInserted.key = arrayOfContents[i].replace("[galerie=\"", "").replace("\"]", "");
}
//else if some other attribute or even create a switch () {}
else {
//insert the normalHtml sanitized
customTagToBeInserted.type = "normal";
customTagToBeInserted.value = this.sanitizer.bypassSecurityTrustHtml(arrayOfContents[i]);
}
arrayWithCustomTags.push(customTagToBeInserted);
}
}
}
else {
arrayWithCustomTags.push({ type: "normal", value: this.sanitizer.bypassSecurityTrustHtml(keyValue.value)});
}
return arrayWithCustomTags;
}
This will create an array like:
[0]: {type: "normal", value:"SecureHTML"},
[1]: {type: "gallery", key:"summer_gallery"},
[2]: {type: "normal", value:"SecureHTML"},
Well I think you get the idea. If you create a whole CMS with more tags I would recommend creating a function that easily creates this whole process (regex etc.) for a tag. This example code is just meant for one tag.
The result is that the components are rendered right where the user places them. I hope this helps you.
Btw, if you have editable key value pairs for the user you might find this helpful: https://github.com/bergben/ng2-ck-editable. It's a little module I built to make any div editable using a ck-editor.
这篇关于Angular 动态组件加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!