Skip to content

Instantly share code, notes, and snippets.

@neilsoult
Last active May 3, 2022 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilsoult/92e2e8414adaac64062e9105b3c49138 to your computer and use it in GitHub Desktop.
Save neilsoult/92e2e8414adaac64062e9105b3c49138 to your computer and use it in GitHub Desktop.
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