]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-custom-markup/dynamic-element.service.ts
208dba721dd8d8fcfc21ee9a0632bf8a4ef07385
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-custom-markup / dynamic-element.service.ts
1 import {
2 ApplicationRef,
3 ComponentRef,
4 createComponent,
5 EmbeddedViewRef,
6 Injectable,
7 Injector,
8 OnChanges,
9 SimpleChange,
10 SimpleChanges,
11 Type
12 } from '@angular/core'
13
14 @Injectable()
15 export class DynamicElementService {
16
17 constructor (
18 private injector: Injector,
19 private applicationRef: ApplicationRef
20 ) { }
21
22 createElement <T> (ofComponent: Type<T>) {
23 const div = document.createElement('div')
24
25 const component = createComponent(ofComponent, {
26 environmentInjector: this.applicationRef.injector,
27 elementInjector: this.injector,
28 hostElement: div
29 })
30
31 return component
32 }
33
34 injectElement <T> (wrapper: HTMLElement, componentRef: ComponentRef<T>) {
35 const hostView = componentRef.hostView as EmbeddedViewRef<any>
36
37 this.applicationRef.attachView(hostView)
38 wrapper.appendChild(hostView.rootNodes[0])
39 }
40
41 setModel <T> (componentRef: ComponentRef<T>, attributes: Partial<T>) {
42 const changes: SimpleChanges = {}
43
44 for (const key of Object.keys(attributes)) {
45 const previousValue = componentRef.instance[key]
46 const newValue = attributes[key]
47
48 componentRef.instance[key] = newValue
49 changes[key] = new SimpleChange(previousValue, newValue, previousValue === undefined)
50 }
51
52 const component = componentRef.instance
53 if (typeof (component as unknown as OnChanges).ngOnChanges === 'function') {
54 (component as unknown as OnChanges).ngOnChanges(changes)
55 }
56
57 componentRef.changeDetectorRef.detectChanges()
58 }
59 }