【问题标题】:Is it possible to add a custom angular element to a component html other than index.html是否可以将自定义角度元素添加到 index.html 以外的组件 html
【发布时间】:2021-03-31 15:30:17
【问题描述】:

使用的 Angular 版本:v11

我正在尝试使用 ngx-build-plus 将具有延迟加载模块的应用程序作为角度元素集成到另一个应用程序中。我在将元素添加到主应用程序中的组件时遇到了一些困难。 当我将它添加到 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 
    }
}

我错过了什么吗?

【问题讨论】:

    标签: angular typescript angular11 angular-elements ngx-build-plus


    【解决方案1】:

    找到了解决办法

    将下面的代码添加到组件(我需要在其中添加角度元素)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多