【问题标题】:How to load an element component with a string in Angular 2如何在Angular 2中加载带有字符串的元素组件
【发布时间】:2022-01-16 19:52:13
【问题描述】:

我创建了一个 angular 元素,我可以通过这样的 url 调用它: http://localhost:8080/elements/ExampleElement.js 这个元素包含一个组件,我想在另一个应用程序中使用它。

在我想要调用组件的应用程序中,我在我的 html 中建立了一些组件的延迟加载,这工作正常:

<example-component *axLazyElement="http://localhost:8080/elements/ExampleElement.js"></example-component>

但是,现在我有一个场景,我将元素组件作为字符串:

""

我想用字符串将它加载到我的组件中。我没有机会单独获取标签“example-component”和网址“http://localhost:8080/elements/ExampleElement.js”。 我的第一个想法是用 innerHtml 来做,但 innerHtml 只适用于一些预定义的标签。

那么您有什么想法吗,如何加载由字符串给出的示例组件?

我正在使用 Angular 12.2.6。

感谢您的帮助!

【问题讨论】:

    标签: angular typescript components load angular-elements


    【解决方案1】:

    axLazyLoading 提供了一些元素的动态加载: angular dynamic lazy loading

    对于这个例子,你可以在你的 html 中编写类似这样的代码:

    <ax-lazy-element *axLazyElementDynamic="'example-component', url: url; module: false">
    </ax-lazy-element>
    

    然后你需要在你的打字稿中定义你的网址:

    url = "http://localhost:8080/elements/ExampleElement.js";
    

    对于此解决方案,您将需要标签名称和元素的 url。如果整个 html 元素只有一个字符串,则可以使用 DOMParser 从字符串中提取标签名称和 url。因此,提取例如标签的函数可能如下所示:

    extractTagFrom(html: string){
        new DOMParser().parseFromString(html, "text/html").documentElement.tagName;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-11
      • 2017-07-04
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 2017-02-17
      • 1970-01-01
      相关资源
      最近更新 更多