]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-custom-markup/dynamic-element.service.ts
Update common client packages
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-custom-markup / dynamic-element.service.ts
CommitLineData
2539932e
C
1import {
2 ApplicationRef,
2539932e 3 ComponentRef,
41cde76b 4 createComponent,
2539932e
C
5 EmbeddedViewRef,
6 Injectable,
7 Injector,
8 OnChanges,
9 SimpleChange,
10 SimpleChanges,
11 Type
12} from '@angular/core'
13
14@Injectable()
15export class DynamicElementService {
16
17 constructor (
18 private injector: Injector,
41cde76b 19 private applicationRef: ApplicationRef
2539932e
C
20 ) { }
21
22 createElement <T> (ofComponent: Type<T>) {
23 const div = document.createElement('div')
24
41cde76b
C
25 const component = createComponent(ofComponent, {
26 environmentInjector: this.applicationRef.injector,
27 elementInjector: this.injector,
28 hostElement: div
29 })
2539932e
C
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}