简体   繁体   English

如何使用纯 JS 导入 2 个或多个 Angular 组件?

[英]How to import 2 or more Angular component with plain JS?

I built an Angular (last version) component I need to import several time into an old school HTML/JS page.我构建了一个 Angular(最新版本)组件,我需要多次将其导入旧式 HTML/JS 页面。

At the moment this Angular component is an HelloWorld component, and when the user clicked a specific element on the plain HTML page I would like to append a new instance of my HelloWorld component:目前,这个 Angular 组件是一个 HelloWorld 组件,当用户单击普通 HTML 页面上的特定元素时,我想 append 我的 HelloWorld 组件的新实例:

<div onclick="divClicked()">Click here to add more component!</div>

At the moment it works for the first click with following code, but not for the others clics:目前,它适用于以下代码的第一次点击,但不适用于其他 clics:

    function divClicked(e) {
        body = document.getElementById("dest")
        app = document.createElement("app-root")
        body.append(app)

        loadScript("dist/angular-app/runtime.js")
        loadScript("dist/angular-app/polyfills.js")
        loadScript("dist/angular-app/main.js")

        console.log("Div clicked", body)
    }

    function loadScript(url) {
        var script = document.createElement('script');
        script.onload = function () {
            console.log("Script loaded", url)
        };
        script.src = url;

        document.head.appendChild(script);
    }

Following clics generates the app-root tag but it's not populate with Angular's content.以下 clics 生成 app-root 标记,但它没有填充 Angular 的内容。 See the generated DOM below:请参阅下面生成的 DOM: 在此处输入图像描述

How can I use many time my component into a pure HTML/JS page?如何将我的组件多次用于纯 HTML/JS 页面?

Hi please use angular elements.您好,请使用 angular 元素。

You can build and make it single js file which you refer in plain HTML and use angular component.您可以构建并使其成为您在普通 HTML 中引用的单个 js 文件,并使用 angular 组件。

Please find below solution:请找到以下解决方案:

https://dev.to/maulik/using-angular-component-in-non-angular-app-1p0g https://dev.to/maulik/using-angular-component-in-non-angular-app-1p0g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM