简体   繁体   中英

Compiling Angular components separate and using them together in an HTML page

I created 2 different Angular projects in the following way:

$ ng new comp-a
$ ng new comp-b

Then, I modified each of them to look different and with each of them I ran the following command to build the corresponding HTML file with the necessary Javascript and CSS files:

$ ng build --base-href "./"

I noticed that on each index.html file generated on each project there are referenced the following Javascript files:

- runtime.js
- polyfills.js
- styles.js
- vendor.js
- main.js

What I want to do:

Create one common HTML file referencing the common files and renaming the non-common files to the component name, something like this:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Testing Angular Components</title>
    <base href="./">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>

    <comp-a></comp-a>
    <comp-b></comp-b>

    <script type="text/javascript" src="runtime.js"></script>
    <script type="text/javascript" src="polyfills.js"></script>
    <script type="text/javascript" src="styles.js"></script>
    <script type="text/javascript" src="vendor.js"></script>
    <script type="text/javascript" src="comp-a.js"></script>
    <script type="text/javascript" src="comp-b.js"></script>

</body>

</html>

Requirements of my goal:

  • I need to generate one Javascript file per each component.
  • I need to use them out of an Angular project like in a normal HTML page like on the example above. Of course I can add the other common Javascript files like on the example above.

Is this possible?

I did a try and didn't work. Maybe, if that's possible, I didn't in the right way. I have to say that I don't have too much experience with Angular.

Thanks!

Two Angular Components in a single Angular Application is what you need.

To demonstrate, lets create a new Angular Application:

ng new my-app

Go to Angular Application folder:

cd my-app

Notice the index.html file that has just been created. Common HTML that you mentioned above can reside in this index.html file. Just preserve <app-root></app-root> tags and everything else can be replaced as you wish.

Then, create two Angular Components:

ng generate component comp1
ng generate component comp2

Edit inside app.component.html file so that this Bootstrap Component would wrap these two recently created Angular Components:

app.component.html:

<app-comp1></app-comp1>
<app-comp2></app-comp2>

Test your Angular Application:

ng serve --open

You should be seeing something like this:

comp1 works! comp2 works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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