-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathweb-component-wrapper.ts
71 lines (58 loc) · 1.68 KB
/
web-component-wrapper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import {
AfterContentInit,
Component,
ElementRef,
Input,
OnChanges,
ViewChild,
} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {
LoadRemoteModuleOptions,
loadRemoteModule,
} from '@angular-architects/module-federation';
export type WebComponentWrapperOptions = LoadRemoteModuleOptions & {
elementName: string;
};
@Component({
// eslint-disable-next-line @angular-eslint/component-selector
selector: 'mft-wc-wrapper',
template: '<div #vc></div>',
})
// eslint-disable-next-line @angular-eslint/component-class-suffix
export class WebComponentWrapper implements AfterContentInit, OnChanges {
@ViewChild('vc', { read: ElementRef, static: true })
vc: ElementRef;
@Input() options: WebComponentWrapperOptions;
@Input() props: { [prop: string]: unknown };
@Input() events: { [event: string]: (event: Event) => void };
element: HTMLElement;
constructor(private route: ActivatedRoute) {}
ngOnChanges(): void {
if (!this.element) return;
this.populateProps();
}
private populateProps() {
for (const prop in this.props) {
this.element[prop] = this.props[prop];
}
}
private setupEvents() {
for (const event in this.events) {
this.element.addEventListener(event, this.events[event]);
}
}
async ngAfterContentInit() {
const options =
this.options ?? (this.route.snapshot.data as WebComponentWrapperOptions);
try {
await loadRemoteModule(options);
this.element = document.createElement(options.elementName);
this.populateProps();
this.setupEvents();
this.vc.nativeElement.appendChild(this.element);
} catch (error) {
console.error(error);
}
}
}