是否可以将自定义 angular 元素添加到组件 html 而不是 index.html

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

Angular 使用的版本:v11

我正在尝试使用 ngx-build-plus 将带有延迟加载模块的应用程序作为 angular 元素集成到另一个应用程序中。我在将元素添加到主应用程序的组件时遇到了一些困难。 当我将它添加到 index.html 时它会呈现,但当我尝试添加到任何其他 html 文件时显示以下错误。

'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模块文件如下

@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 
    }
}

我是不是遗漏了什么?

找到了解决方案

将以下代码添加到 component(我需要在其中添加 angular 元素)。

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

el: 元素引用

加载外部文件服务

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);
}