项目作者: brunob15

项目描述 :
Angular Element that allows lazy loading Angular components in non-angular applications
高级语言: TypeScript
项目地址: git://github.com/brunob15/ngx-element.git
创建时间: 2020-02-25T18:24:16Z
项目社区:https://github.com/brunob15/ngx-element

开源协议:

下载


npm version
Tests CI

NgxElement

NgxElement enables to lazy load Angular components in non-angular applications.
The library will register a custom element to which you can pass an attribute to specify what component you want to load.

It’s a great way to use Angular in your CMS platform in an efficient manner.

Install Angular Elements

This library depends on Angular Elements. You can install it by running:

  1. $ ng add @angular/elements

Installing the library

  1. $ npm install ngx-element --save

Usage

1) Configure the Module containing the lazy loaded component

First of all, expose the Angular Component that should be loaded via a customElementComponent property.

  1. ...
  2. @NgModule({
  3. declarations: [TalkComponent],
  4. ...
  5. exports: [TalkComponent],
  6. entryComponents: [TalkComponent]
  7. })
  8. export class TalkModule {
  9. customElementComponent: Type<any> = TalkComponent;
  10. ...
  11. }

2) Define the lazy component map in your AppModule

Just like with the Angular Router, define the map of component selector and lazy module.

  1. const lazyConfig = [
  2. {
  3. selector: 'talk',
  4. loadChildren: () => import('./talk/talk.module').then(m => m.TalkModule)
  5. }
  6. ];
  7. @NgModule({
  8. ...,
  9. imports: [
  10. ...,
  11. NgxElementModule.forRoot(lazyConfig)
  12. ],
  13. ...
  14. })
  15. export class AppModule {
  16. ...
  17. ngDoBootstrap() {}
  18. }

3) Use the lazy loaded component

You can load your Angular component by adding an <ngx-element> tag to the DOM in your non-angular application like follows:

  1. <ngx-element
  2. selector="talk"
  3. data-title="Angular Elements"
  4. data-description="How to write Angular and get Web Components"
  5. data-speaker="Bruno">
  6. </ngx-element>

4) Listen to events

You can listen to events emitted by Angular components.

Add an @Output event to your component:

  1. ...
  2. @Output() tagClick: EventEmitter<string> = new EventEmitter();
  3. ...

Then add an event listener to the tagClick event on the appropiate <ngx-element> element:

  1. const talks = document.querySelector('ngx-element[selector="talk"]');
  2. talks.addEventListener('tagClick', event => {
  3. const emittedValue = event.detail;
  4. ...
  5. });

Credits

Thanks to Juri Strumpflohner and ngx-lazy-el!