Angular Elements are angular components that can be published as web components, making them easy to reuse on any hTML page. This article will show you how to implement angular elements in your web applications.
Angular Element is a new package in angular that helps us to publish angular components as custom elements. It does this by compiling the angular part into a web component. The Angular Elements functionality is available with the package @angular/elements.
Let’s get into implementation
1. Firstly, create a new project by hitting the command.
ng new angular-custom-elements-demo
2. Add elements package by hitting the command.
ng add @angular/elements
3. Then create a component.
ng g component button --inline-style --inline-template
4. After that, add properties to the component.
import { Component, OnInit ,EventEmitter, Input, OnChanges, Output, SimpleChanges, ViewEncapsulation} from '@angular/core'; @Component({ selector: 'app-button', template: ` <div> <h2 style="text-align:center">Mindbowser | Angular Elements</h2> <form style="margin-left: 410px;"> <label>Name</label> <input type= "text" name = "Name"[(ngModel)] = "Name"> <label>Email</label> <input type= "text" name= "Email"[(ngModel)] = "Email"> <button (click)="handleClick($event)">{{ label }}</button> </form> </div> `, styles: ['input[type=text], select {width: 50%;padding: 12px 20px;margin: 8px 0;display: flex;border: 1px solid #ccc;border-radius: 4px;box-sizing: border-box;}button {width: 50%;background-color: #24a0ed;color: white;padding: 14px 20px;margin: 8px 0;border: none;border-radius: 4px;cursor: pointer;}button:hover {background-color: #24a0ed;}div {border-radius: 5px;background-color: #f2f2f2;padding: 20px;}'], }) export class ButtonComponent implements OnChanges { @Input() label = ''; @Output() action = new EventEmitter<String>(); Name = ''; Email = ''; constructor() { } ngOnChanges(changes: SimpleChanges) { console.log(changes); } handleClick(event: any) { let details = `{Name: ${this.Name}, Email: ${this.Email}}` this.action.emit(details); } }
5. Update NgModule.
import { NgModule, Injector } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ButtonComponent } from './button/button.component'; import { createCustomElement } from '@angular/elements'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, ButtonComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule ], entryComponents: [ButtonComponent], providers: [] }) export class AppModule { constructor(private injector: Injector) { } // to use this module for bootstrapping ngDoBootstrap() { // for converting an angular component together with its dependencies to a custom element const customElement = createCustomElement(ButtonComponent, {injector: this.injector}); customElements.define('app-button', customElement); } }
6. Here, we have removed the bootstrap array, which is set to AppComponent. Then, add the ButtonComponent as the entryComponent list. Then, we said ngDoBootstrap() to use this module for bootstrapping.
7. Angular provides createCustomElement() for converting an Angular component with its dependencies to a custom element. And it accepts two parameters.
👉 First, the angular component should be used to create the element.
👉 Second, a configuration object. This object needs to include the injector property set to the current Injector instance.
8. The next step is registering the newly created custom element in the browser.This is done by calling customElements.define().
9. customElements.define() needs two parameter.
👉 First parameter is of type string and contains the name of the element.
Passing the string ‘app-button’ means the custom element <app-button> will be registered and can be used in HTML code.
👉 The second parameter is the custom element which has been created before.
10. After that, we need to build our project. Also, we need to concatenate 4 files(runtime.js, scripts.js, polyfills.js and main.js). After doing the project, a static js file will be created. And this we need to include in <script> an HTML page to see if our custom element is working.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>AngularCustomElements</title> <script src="./custom-button-element.js"></script> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-button label="Submit" ></app-button> <script> const button = document.querySelector('app-button'); button.addEventListener('action', (event) => { console.log(`Action created: ${event.detail}`); }); </script> </body> </html>
1. For this, we need to create a new Angular project by hitting the command.
ng new my-app
2. After that, we need to run the command.
npm install web-component-essentials
This command will install our Angular project’s web component and add an entry into the package JSON.
3. Once imported, add CUSTOM_ELEMENTS_SCHEMA from @angular/core to the application module.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import 'web-component-essentials'; import '../assets/custom-button-element.js'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent], schemas: [ CUSTOM_ELEMENTS_SCHEMA // Tells Angular we will have custom tags in our templates ] }) export class AppModule { }
4. Import the static js file that has been generated at our main project to the application module.
5. Then, copy the selector for a custom element from the index.js file of our main project, paste it and run our new project.
Here’s the Html File:
<h1 style="text-align: center;">Importing An Angular Element</h1> <app-button #ButtonComponent label="Submit" formName="Form"> </app-button> {{receivedData}}
import { Component, AfterViewInit, ElementRef} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'my-app'; button: any; receivedData='' constructor(private elementref: ElementRef){ } ngAfterViewInit(){ this.elementref.nativeElement.querySelector('app-button').addEventListener('action', (event: any) => { console.log(`Action created: ${event.detail}`); this.receivedData = event.detail }); } }
This is the whole procedure, from creating an angular element to importing this into an entirely new project. Here’s the output.
Related Read : What Are Micro-Frontends And Steps To Implement Micro-Frontends In Angular
We have seen how to implement Angular elements, and importing angular element to another project. Angular Elements are the future of Angular, and are part of the reason why Angular is so successful.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork