]>
Commit | Line | Data |
---|---|---|
2539932e C |
1 | import { |
2 | ApplicationRef, | |
3 | ComponentFactoryResolver, | |
4 | ComponentRef, | |
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 | private componentFactoryResolver: ComponentFactoryResolver | |
21 | ) { } | |
22 | ||
23 | createElement <T> (ofComponent: Type<T>) { | |
24 | const div = document.createElement('div') | |
25 | ||
26 | const component = this.componentFactoryResolver.resolveComponentFactory(ofComponent) | |
27 | .create(this.injector, [], div) | |
28 | ||
29 | return component | |
30 | } | |
31 | ||
32 | injectElement <T> (wrapper: HTMLElement, componentRef: ComponentRef<T>) { | |
33 | const hostView = componentRef.hostView as EmbeddedViewRef<any> | |
34 | ||
35 | this.applicationRef.attachView(hostView) | |
36 | wrapper.appendChild(hostView.rootNodes[0]) | |
37 | } | |
38 | ||
39 | setModel <T> (componentRef: ComponentRef<T>, attributes: Partial<T>) { | |
40 | const changes: SimpleChanges = {} | |
41 | ||
42 | for (const key of Object.keys(attributes)) { | |
43 | const previousValue = componentRef.instance[key] | |
44 | const newValue = attributes[key] | |
45 | ||
46 | componentRef.instance[key] = newValue | |
47 | changes[key] = new SimpleChange(previousValue, newValue, previousValue === undefined) | |
48 | } | |
49 | ||
50 | const component = componentRef.instance | |
51 | if (typeof (component as unknown as OnChanges).ngOnChanges === 'function') { | |
52 | (component as unknown as OnChanges).ngOnChanges(changes) | |
53 | } | |
54 | ||
55 | componentRef.changeDetectorRef.detectChanges() | |
56 | } | |
57 | } |