这是一个在Angular 5+上完美运行的解决方案。对于Angular 6,我尚未进行过此操作。我已经在一个大型CMS项目中完成了此操作,并在多个页面中插入了组件,甚至在同一页中插入了两个相同的Angular模块。您可以使用一个Angular项目。在您的站点中,编写组件标记。您需要创建另一个模块(例如mainHelper),以导出每个选定的Angular标记。
import {NgModule, ApplicationRef, ComponentFactoryResolver} from '@angular/core';
import {FirstModule} from 'YOUR MODULE PATH';
import {FirstComponent} from 'YOU COMPONENT PATH';
import {SecondModule} from 'YOUR MODULE PATH';
import {SecondComponent} from 'YOU COMPONENT PATH';
@NgModule({
imports: [
FirstModule,
SecondModule
],
})
export class MainHelper {
constructor(private resolver: ComponentFactoryResolver) {
}
components = [
FirstComponent,
SecondComponent
];
ngDoBootstrap(ref: ApplicationRef) {
this.components.forEach((component) => {
const factory = this.resolver.resolveComponentFactory(component);
const elements = document.getElementsByTagName(factory.selector);
if (elements.length > 0) {
if (elements.length > 1) {
const selector = factory.selector;
for (let i = 0; i < elements.length; i++) {
elements[i].id = selector + '-' + i;
(<any>factory).factory.selector = '#' + elements[i].id;
ref.bootstrap((<any>factory).factory);
}
(<any>factory).factory.selector = selector;
} else {
ref.bootstrap(component);
}
}
});
}
}
在你的 main.ts 中,你可以导入 MainHelper 模块并启动 MainHelper。
你的 FirstModule 应该是这样的:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {BrowserModule} from '@angular/platform-browser';
import {FirstComponent} from './first.component';
import {AnotherComponent} from './another/another.component';
@NgModule({
imports: [
CommonModule,
BrowserModule,
],
providers: [
SampleService
],
declarations: [
FirstComponent,
AnotherComponent,
],
bootstrap: [FirstComponent]
})
export class ECommerceModule {
}
我希望这可以帮助你。