Last active
May 3, 2022 14:30
-
-
Save neilsoult/92e2e8414adaac64062e9105b3c49138 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, createNgModuleRef, Injector, Input, OnChanges, ViewChild } from '@angular/core'; | |
import { loadRemoteModule } from '@nrwl/angular/mfe'; | |
import { PluginDirective } from './plugin-directive'; | |
// plugin directive: | |
// import { Directive, ViewContainerRef } from '@angular/core'; | |
// @Directive({ selector: '[crxPlugin]' }) | |
// export class PluginDirective { | |
// constructor (public viewContainerRef: ViewContainerRef) { } | |
// } | |
interface ComponentWithResolve<T> { | |
resolve: T; | |
}; | |
interface RemotePluginOptions { | |
moduleName: string; | |
remoteModule: string; | |
remoteName: string; | |
}; | |
@Component({ | |
selector: 'crx-remote-plugin', | |
template: '<ng-template crxPlugin></ng-template>' | |
}) | |
export class RemotePluginComponent<T extends ComponentWithResolve<ResolveType>, ResolveType> implements OnChanges { | |
@Input() options!: RemotePluginOptions; | |
@Input() resolve?: ResolveType; | |
@ViewChild(PluginDirective, { static: true }) plugin!: PluginDirective; | |
constructor (private injector: Injector) {} | |
async ngOnChanges () { | |
this.plugin.viewContainerRef.clear(); | |
const module = await loadRemoteModule(this.options.remoteName, this.options.moduleName); | |
const remoteModule = module[this.options.remoteModule]; | |
if (remoteModule) { | |
// ngModuleRef is needed if your remote is more than just a single component. This allows us | |
// to load other dependencies and providers for the remote | |
const ngModuleRef = createNgModuleRef(remoteModule, this.injector); | |
const componentRef = this.plugin.viewContainerRef | |
.createComponent<T>(remoteModule.component, { ngModuleRef }); | |
if (componentRef && this.resolve) { | |
componentRef.instance.resolve = this.resolve; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment