【问题标题】:How can I dynamically load Angular components in subsections of a document being loaded as innerHtml?如何在作为 innerHtml 加载的文档的子部分中动态加载 Angular 组件?
【发布时间】:2021-01-10 15:31:24
【问题描述】:

我有一个 Angular 组件,“app-xml-content”。

在 app-xml-content 中,我从外部源加载了一些 XML。然后我想突出显示该 XML 的某些部分,并添加一个包含一些有用信息的工具提示。

我做到了如下:

<div id="xml-content" [innerHTML]="xmlString | customHighlight: criteria"></div>

我的 customHighlight 管道将搜索 XML,目前只是进行 RegEx 替换:

const highlighter = (match) => `<mark class="highlight${diff.intensity}">${match}</mark>`;
if (diff.intensity) {
    modifiedContent = modifiedContent.replace(new RegExp(pattern, 'gi'), highlighter);
}

但我更希望荧光笔用自定义 Angular 组件替换匹配项,而不是 HTML &lt;mark /&gt;。例如

const highlighter = (match) => `<app-highlight intensity="${diff.intensity}" content="${match}"></app-highlight>`;
if (diff.intensity) {
    modifiedContent = modifiedContent.replace(new RegExp(pattern, 'gi'), highlighter);
}

当我这样做时,突出显示的部分根本不会呈现。

我可以看到&lt;app-highlight /&gt; 的构造函数没有被调用。

我进行了调查,发现了ComponentFactoryResolver,但我真的不明白如何使用它来仅呈现被替换的 XML 位。我可以使用管道中的解析器将其解析为 AppHighlightComponent 吗?

如果有人可以向我展示一个我可以使用的模式来帮助我解决这个问题,我将不胜感激。

谢谢。

【问题讨论】:

    标签: javascript angular innerhtml


    【解决方案1】:

    一种可能的解决方案是使用 Angular 元素从您的 Angular 组件创建一个 Web 组件。为此,您需要在 AppModule 中添加 AppHighlight 作为入口组件,将其声明为自定义元素和 ngDoBootsrap 方法。

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule, DoBootstrap, Injector } from '@angular/core';
    import { createCustomElement } from '@angular/elements';
    import { AppHightlight } from 'path/to/AppHighlight';
    
    @NgModule({
      declarations: [
        AppHighlight,
      ],
      imports: [
        BrowserModule,
      ],
      entryComponents: [AppHighlight],
    })
    export class AppModule implements DoBootstrap {
    
      constructor(private injector: Injector) {
        const webComponent = createCustomElement(AppHighlight, {injector});
        customElements.define('custom-app-highlight', webComponent);
      }
    
      ngDoBootstrap() {}
    }
    

    然后,每当在 DOM 中注入 custom-app-highlight 时,您的浏览器都会将其解释为您的 Angular 组件。

    <div>
        <custom-app-highlight intensity="intensity string" content="content string" />
    </div>
    

    编辑 1:请注意,角度元素的输入不能包含大写字母,它们应该是字符串 编辑 2:删除了指向 angular 元素的链接,以给出一个带有代码的实现示例

    【讨论】:

    • 您能详细说明一下这个答案吗?链接通常被认为是不充分的答案,因为 StackOverflow 不能保证该链接将永远可用 - 所以在某些时候它可能会成为一个毫无价值的答案。
    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 2017-10-27
    • 2021-12-20
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多