- Add
@angular/elements
$ ng add @angular/elements --project=[project-name]
- Add nessry polyfills
$ npm i @webcomponents/custom-elements --save
- Don't forget to add it to
polyfills.ts
file
import '@webcomponents/custom-elements/src/native-shim';
import '@webcomponents/custom-elements/custom-elements.min';
- Create your component
$ ng g c [angular-element]
- Just change ViewEncapsulation to be Native
@Component({
selector: 'angular-element',
templateUrl: './angular-element.component.html',
styleUrls: ['./angular-element.component.css'],
encapsulation: ViewEncapsulation.Native
})
- Change your module to use custom element
// Angular imports
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
// Component that needs to convert it to customElement
import { AngularElementComponent } from './angular-element/angular-element.component';
@NgModule({
declarations: [AngularElementComponent],
imports: [BrowserModule],
providers: [],
entryComponents: [AngularElementComponent]
})
export class AppModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
// using createCustomElement from angular package it will convert angular component to stander web component
const el = createCustomElement(AngularElementComponent, {
injector: this.injector
});
// using built in the browser to create your own custome element name [HTML Tag]
customElements.define('web-element', el);
}
}
- Build
Run ng build --project=[project-name]
to build the element.
The build artifacts will be stored in the dist/[project-name] directory.
- Type
npm install
in your termainal to install packages dependencies - Type
npm run serve:ng-element
in your termainal to start card project - You code live and running at http://localhost:4200