Last active
August 29, 2022 14:09
-
-
Save NetanelBasal/c5400668b8fd89c682854dbed7d0b0fa to your computer and use it in GitHub Desktop.
This file contains 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 { Directive, ElementRef, Input } from '@angular/core'; | |
import type { ComponentProps, ElementType } from 'react'; | |
import type { Root } from 'react-dom/client'; | |
@Directive({ | |
selector: '[lazyReactComponent]', | |
standalone: true | |
}) | |
export class LazyReactComponentDirective<Comp extends ElementType> { | |
@Input() lazyReactComponent: () => Promise<Comp>; | |
@Input() props: ComponentProps<Comp>; | |
private root: Root | null = null; | |
constructor(private host: ElementRef) { } | |
async ngOnChanges() { | |
const [{ createElement }, { createRoot }, Comp] = await Promise.all([ | |
import('react'), | |
import('react-dom/client'), | |
this.lazyReactComponent() | |
]); | |
if (!this.root) { | |
this.root = createRoot(this.host.nativeElement); | |
} | |
this.root.render(createElement(Comp, this.props)) | |
} | |
ngOnDestroy() { | |
this.root?.unmount(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment