Is it possible to add a custom angular element to a component html other than index.html

1k Views Asked by At

Angular version used: v11

I am trying to integrate an application with lazy loaded modules as angular elements using ngx-build-plus into another application. I am having some difficulty adding the element to a component in the main application. When I add it to the index.html it will render, but showing below error when i try to add to any other html file.

'cs-root' is not a known element:
1. If 'cs-root' is an Angular component, then verify that it is part of this module.
2. If 'cs-root' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

App module file is as below

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    RouterModule,
    AppRoutingModule,
    CoreModule.forRoot(),
    SharedModule.forRoot(),
    ToasterModule
  ],
  exports: [AppComponent],
  providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpAuthInterceptor, multi: true },
    { provide: APP_INITIALIZER, useFactory: appInitFactory, deps: [AppInitService], multi: true },
     WindowService,
     InsightsGuard],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(private injector: Injector) {
    const el = createCustomElement(AppComponent, { injector });
    customElements.define('cs-root', el);
  }
  ngDoBootstrap() {
    // This method circumvents the natural bootstrapping of the element 
    }
}

am i missing something here ?

1

There are 1 best solutions below

0
On BEST ANSWER

found a solution for this

added below code to component (in which I need to add the angular element).

if (!document.getElementById('cs-root')) {
   this.loadExternalService.addExternalScript(renderer2);
   const customElement = document.createElement('cs-root');
   const contentHolder = this.el.nativeElement;
   contentHolder.appendChild(customElement);
}

el: ElementRef

load-external-files service

const customPath = 'http://localhost:4600/'
public addExternalScript(renderer2: Renderer2): void {
   const script = renderer2.createElement('script');
   script.type = 'text/javascript';
   script.text = ``;
   script.src = `${customPath}[es2015-bundle-file-name].js`;
   script.onload = this.loadNextScript.bind(this, renderer2, cdnUrl);
   renderer2.appendChild(this._document.body, script);
}
private loadNextScript(renderer2: Renderer2) {
  const script = renderer2.createElement('script');
  script.type = 'text/javascript';
  script.text = ``;
  script.src = `${customPath}[es5-bundle-file-name].js`;
  script.onload = () => {
       // logic on files load
  };
  renderer2.appendChild(this._document.body, script);
}