Skip to content

Commit

Permalink
feat: add new api for creating interactive angular component formatters
Browse files Browse the repository at this point in the history
  • Loading branch information
vsoftic committed Oct 25, 2023
1 parent 3d2ce77 commit 71d2132
Showing 1 changed file with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,31 @@ export class AngularUtilService {

constructor(private vcr: ViewContainerRef) { }

createInteractiveAngularComponent<C>(component: Type<C>, targetElement: Element, data?: any, createCompOptions?: CreateComponentOption): AngularComponentOutput {
// Create a component reference from the component
const componentRef = this.vcr.createComponent(component, createCompOptions);

// user could provide data to assign to the component instance
if (componentRef?.instance && data) {
Object.assign(componentRef.instance as any, data);
}

// Get DOM element from component
let domElem: HTMLElement | null = null;
const viewRef = (componentRef.hostView as EmbeddedViewRef<any>);

if (viewRef && Array.isArray(viewRef.rootNodes) && viewRef.rootNodes[0]) {
domElem = viewRef.rootNodes[0] as HTMLElement;

// when user provides the DOM element target, we will move the dynamic component into that target (aka portal-ing it)
if (targetElement && domElem) {
targetElement.replaceChildren(componentRef.location.nativeElement);
}
}

return { componentRef, domElement: domElem as HTMLElement };
}

/**
* Dynamically create an Angular component, user could also provide optional arguments for target, data & createComponent options
* @param {Component} component
Expand All @@ -33,7 +58,7 @@ export class AngularUtilService {
if (componentRef?.instance && data) {
Object.assign(componentRef.instance as any, data);

// NOTE: detectChanges() MUST be doene BEFORE returning the DOM element in the next step,
// NOTE: detectChanges() MUST be done BEFORE returning the DOM element in the next step,
// because if we do it only after returning the rootNodes (domElement) then it won't have the instance data yet
// and we would have to wait an extra cycle to see the result, this basically helps with Example22
componentRef.changeDetectorRef.detectChanges();
Expand Down

0 comments on commit 71d2132

Please sign in to comment.