-
-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathindex.ts
More file actions
57 lines (49 loc) · 2 KB
/
index.ts
File metadata and controls
57 lines (49 loc) · 2 KB
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
import type { LifeCycles } from 'single-spa';
import type { NgElement } from '@angular/elements';
import {
type BaseSingleSpaAngularOptions,
getContainerElementAndSetTemplate,
} from '@single-spa-community/angular/internals';
import type { BootstrappedSingleSpaAngularElementsOptions } from './types';
const defaultOptions: BootstrappedSingleSpaAngularElementsOptions = {
element: null,
template: null!,
ngModuleRefOrAppRef: null,
bootstrapFunction: null!,
domElementGetter: undefined,
};
async function bootstrap(options: BootstrappedSingleSpaAngularElementsOptions, props: any) {
if (options.ngModuleRefOrAppRef !== null) {
return;
}
// We call `bootstrapFunction()` inside the bootstrap lifecycle hook
// because Angular modules that expose custom elements should be
// bootstrapped only once.
options.ngModuleRefOrAppRef = await options.bootstrapFunction(props);
}
async function mount(options: BootstrappedSingleSpaAngularElementsOptions, props: any) {
const containerElement = getContainerElementAndSetTemplate(options, props);
// `options.template` which can be `<app-element />` is not a valid selector
// for `document.querySelector`, thus we retrieve this custom element
// via this property.
options.element = containerElement.firstElementChild as NgElement;
}
function unmount(options: BootstrappedSingleSpaAngularElementsOptions): Promise<void> {
return Promise.resolve().then(() => {
// Removing custom element from DOM is enough since it will trigger
// `disconnectedCallback()` and Angular will dispose all resources.
options.element!.parentElement!.removeChild(options.element!);
options.element = null;
});
}
export function singleSpaAngularElements(userOptions: BaseSingleSpaAngularOptions): LifeCycles {
const options: BootstrappedSingleSpaAngularElementsOptions = {
...defaultOptions,
...userOptions,
};
return {
bootstrap: bootstrap.bind(null, options),
mount: mount.bind(null, options),
unmount: unmount.bind(null, options),
};
}