aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/shared-custom-markup/dynamic-element.service.ts
blob: e967e30ac74961758227efdcd77e03c83812beeb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import {
  ApplicationRef,
  ComponentFactoryResolver,
  ComponentRef,
  EmbeddedViewRef,
  Injectable,
  Injector,
  OnChanges,
  SimpleChange,
  SimpleChanges,
  Type
} from '@angular/core'

@Injectable()
export class DynamicElementService {

  constructor (
    private injector: Injector,
    private applicationRef: ApplicationRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) { }

  createElement <T> (ofComponent: Type<T>) {
    const div = document.createElement('div')

    const component = this.componentFactoryResolver.resolveComponentFactory(ofComponent)
      .create(this.injector, [], div)

    return component
  }

  injectElement <T> (wrapper: HTMLElement, componentRef: ComponentRef<T>) {
    const hostView = componentRef.hostView as EmbeddedViewRef<any>

    this.applicationRef.attachView(hostView)
    wrapper.appendChild(hostView.rootNodes[0])
  }

  setModel <T> (componentRef: ComponentRef<T>, attributes: Partial<T>) {
    const changes: SimpleChanges = {}

    for (const key of Object.keys(attributes)) {
      const previousValue = componentRef.instance[key]
      const newValue = attributes[key]

      componentRef.instance[key] = newValue
      changes[key] = new SimpleChange(previousValue, newValue, previousValue === undefined)
    }

    const component = componentRef.instance
    if (typeof (component as unknown as OnChanges).ngOnChanges === 'function') {
      (component as unknown as OnChanges).ngOnChanges(changes)
    }

    componentRef.changeDetectorRef.detectChanges()
  }
}