Angular 17 通用(SSR)+独立组件+WebComponents(Angular 元素)

问题描述 投票:0回答:1

是否可以使用独立组件创建一个 Angular 17 通用项目,同时还具有 Web 组件(Angular 元素)?

我正在尝试从 Angular 16 项目导入一个组件(常规组件),该项目是作为 Angular 元素(WebComponent)创建的,它允许我将其“导入”到外部 .html 文件中(只需导入 main.js、polyfills) .js、runtime.js、scripts.js 和 styles.css)来自 Angular dist 目录

以下是我之前在外部 HTML 文件中导入组件的方法:

<comments-widget token="token" context="main_app" rel_ext_type="deliveries" rel_ext_id="14"></comments-widget>

最初,在

app.module
中,我有:

export class AppModule implements DoBootstrap {
    constructor(private injector: Injector, public globalConfig: GlobalConfigService) {}

    ngDoBootstrap(appRef: ApplicationRef) {
        if (document.querySelector('app-root')) {
            appRef.bootstrap(AppComponent);
        } else {
            // create global var here
            this.globalConfig.ExMode = true;

            // Comments
            const commentsWidget = createCustomElement(CommentsComponent, { injector: this.injector });
            customElements.define('comments-widget', commentsWidget);
        }
    }
}

我现在已经将

CommentsComponent
修改为 Angular 17 SSR 项目中的独立组件,并且运行良好。但是,当尝试将其用作
main.js
文件中的 WebComponent 时:

import { createApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { createCustomElement } from '@angular/elements';
import { CommentsComponent } from './app/comments/comments.component';

(async () => {
    const app = await createApplication(appConfig);

    const commentsElement = createCustomElement(CommentsComponent, { injector: app.injector });

    customElements.define('comments-widget', commentsElement);
})();

这似乎不起作用。关于可能导致此问题的原因或我如何解决它有任何想法吗?

angular angular-universal angular-elements angular-standalone-components angular17
1个回答
0
投票

您可以从本文中获取一些想法https://www.angulararchitects.io/en/blog/micro-frontends-with-modern-angular-part-2-multi-version-and-multi-framework-solutions-带有角度元素和网络组件/

  1. 检查您是否有正确的选择器
  2. 添加globalThis.ngZone
  3. 添加路由处理connectRouter()
© www.soinside.com 2019 - 2024. All rights reserved.