Skip to content

Instantly share code, notes, and snippets.

View JiaLiPassion's full-sized avatar
🏠
Working from home

JiaLiPassion JiaLiPassion

🏠
Working from home
View GitHub Profile
class AngularCustomElementBridge {
prepare(injector, component) {
this.componentFactory = injector.get(ComponentFactoryResolver).resolveComponentFactory(component);
// we use templateName to handle this case @Input('aliasName');
this.observedAttributes = componentFactory.inputs.map(input => input.templateName);
}
}
class AngularCustomElementBridge {
setInputValue(propName, value) {
  if (!this.componentRef) {
this.initialInputValues[propName] = value;
return;
}
if (this.componentRef[propName] === value) {
return;
}
this.componentRef[propName] = value;
class AngularCustomElementBridge {
destroy() {
this.componentRef.destroy();
}
}
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
this.componentFactory = injector.get(ComponentFactoryResolver).resolveComponentFactory(component);
this.observedAttributes = componentFactory.inputs.map(input => input.templateName); // we use templateName to handle this case @Input('aliasName');
callback summary angular part
constructor initialize internalstate do some preparation work
connectedCallback initialize View/Event Listener Load Angular Component
disconnectedCallback clear View/Event Listener Destroy Angular Component
attributeChangedCallback Handle attribute change Handle @Input Change
class HelloComponentClass extends HTMLElement {
  constructor() {
  super();
  }
  static get observedAttributes() {
  }
  connectedCallback() {
  }
import { Component, Input } from '@angular/core';
@Component({
  selector: 'app-hello',
  template: `<div>{{name}}</div>`
})
export class HelloComponent {
  @Input() name: string;
}
callback summary 
constructor initialize state or shadowRoot if needed
connectedCallback Will be called when element is added to DOM
disconnctedCallback Will be called when element is removed from DOM
attributeChangedCallback Will be called when attribute of the element change
class AppHello extends HTMLElement {
  constructor() {
  super();
  }
  // define which attributes need to be observed so attributeChangedCallback will be triggered
  // when according attribute changed.
  static get observedAttributes() {return ['name']; }
  // getter to do a attribute -> property reflection