Skip to content

Instantly share code, notes, and snippets.

@JiaLiPassion
Last active June 23, 2018 05:12
Show Gist options
  • Save JiaLiPassion/b9fe81636493b4929f1b926579629395 to your computer and use it in GitHub Desktop.
Save JiaLiPassion/b9fe81636493b4929f1b926579629395 to your computer and use it in GitHub Desktop.
class AngularCustomElementBridge {
initComponent(element: HTMLElement) {
// first we need an componentInjector to initialize the component.
// here the injector is from outside of Custom Element, user can register some of their own
// providers in it.
const componentInjector = Injector.create([], this.injector);
this.componentRef = this.componentFactory.create(componentInjector, null, element);
// Then we need to check whether we need to initialize value of component's input
// the case is, before Angular Element is loaded, user may already set element's property.
// those values will be kept in an initialInputValues map.
this.componentFactory.inputs.forEach(prop => this.componentRef.instance[prop.propName] = this.initialInputValues[prop.propName]);
// then we will trigger a change detection so the component will be rendered in next tick.
this.changeDetectorRef.detectChanges();
this.applicationRef = this.injector.get(ApplicationRef);
// finally we will attach this component's HostView to applicationRef
this.applicationRef.attachView(this.componentRef.hostView);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment