π Welcome the guide on how to include an entire Angular app with routing inside a web component!
Will be used @angular/elements
to create a web component in Angular, and the entire app will be included inside it.
- Clone the repository
- Install dependencies using
npm install
- Build using
ng build
- Package to compile the
dist/*.*.js
angular build intoangular-in-web-component.js
usingnpm run package
- Serve using
npm run serve
Here are the relevant commands:
"start": "ng serve",
"build": "ng build",
"package": "cat ./dist/angular-in-web-component/{polyfills,runtime,main}.*.js > ./test-angular-web-component/angular-in-web-component.js && cp ./dist/angular-in-web-component/styles.*.css ./test-angular-web-component/styles.css",
"serve": "npx -p http-server http-server ./test-angular-web-component/ -o --cors --port 8080 -P http://localhost:8080?",
The package
command will copy also the generated style file styles.css
into the test-angular-web-component
directory.
Here is the file tree:
βββ angular-in-web-component.js
βββ index.html
βββ styles.css
Install @angular/elements
with the following command:
npm i @angular/elements -D
In app.module.ts
, use @angular/elements
to include the AppComponent
component and define it with customElements.define
.
Remember to set the same selector in AppComponent
as the one used in customElements.define
.
Here is the file tree of the app:
.
βββ app
β βββ app-routing.module.ts
β βββ app.component.html
β βββ app.component.scss
β βββ app.component.ts
β βββ app.module.ts
β βββ home
β βββ container
β β βββ home.component.html
β β βββ home.component.scss
β β βββ home.component.ts
β βββ home-routing.module.ts
β βββ home.module.ts
βββ assets
βββ favicon.ico
βββ index.html
βββ main.ts
βββ styles.scss
There is another module inside the app called home
, which can be accessed at /home
to test routing.
That's it! You can now include the Angular app with routing inside a web component.
Happy coding! π»