Skip to content

Instantly share code, notes, and snippets.

@NetanelBasal
Last active August 29, 2022 14:09
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 NetanelBasal/c5400668b8fd89c682854dbed7d0b0fa to your computer and use it in GitHub Desktop.
Save NetanelBasal/c5400668b8fd89c682854dbed7d0b0fa to your computer and use it in GitHub Desktop.
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