问题描述
使用的 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.
应用模块文件如下
@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],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
}
}
我在这里遗漏了什么吗?
解决方法
找到了解决方案
将下面的代码添加到组件(其中我需要添加角度元素)。
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);
}