@@ -11,6 +11,8 @@ import { DOCUMENT } from '@angular/platform-browser';
11
11
*/
12
12
@Injectable ( )
13
13
export class ComponentsHelper {
14
+ public root :ViewContainerRef ;
15
+
14
16
public constructor ( private applicationRef :ApplicationRef ,
15
17
private componentFactoryResolver :ComponentFactoryResolver ,
16
18
private injector :Injector ) {
@@ -21,25 +23,36 @@ export class ComponentsHelper {
21
23
}
22
24
23
25
/**
24
- * This is a name conventional class to get application root view component ref
26
+ * In some cases, like using ngUpgrate,
27
+ * you need to explicitly set view container ref
25
28
* to made this method working you need to add:
26
29
* ```typescript
27
30
* @Component ({
28
31
* selector: 'my-app',
29
32
* ...
30
33
* })
31
34
* export class MyApp {
32
- * constructor(viewContainerRef: ViewContainerRef) {
35
+ * constructor(componentsHelper:ComponentsHelper, viewContainerRef: ViewContainerRef) {
33
36
* // A Default view container ref, usually the app root container ref.
34
37
* // Has to be set manually until we can find a way to get it automatically.
35
- * this. viewContainerRef = viewContainerRef;
38
+ * componentsHelper.setRootViewContainerRef( viewContainerRef)
36
39
* }
37
40
* }
38
41
* ```
42
+ */
43
+ public setRootViewContainerRef ( value :ViewContainerRef ) :void {
44
+ this . root = value ;
45
+ }
46
+ /**
47
+ * This is a name conventional class to get application root view component ref
39
48
* @returns {ViewContainerRef } - application root view component ref
40
49
*/
41
50
public getRootViewContainerRef ( ) :ViewContainerRef {
42
51
// https://github.com/angular/angular/issues/9293
52
+ if ( this . root ) {
53
+ return this . root ;
54
+ }
55
+
43
56
const comps = this . applicationRef . components ;
44
57
45
58
if ( ! comps . length ) {
@@ -48,8 +61,9 @@ export class ComponentsHelper {
48
61
49
62
try {
50
63
/* one more ugly hack, read issue above for details */
51
- const root = ( this . applicationRef as any ) . _rootComponents [ 0 ] ;
52
- return root . _hostElement . vcRef ;
64
+ const rootComponent = ( this . applicationRef as any ) . _rootComponents [ 0 ] ;
65
+ this . root = rootComponent . _hostElement . vcRef ;
66
+ return this . root ;
53
67
} catch ( e ) {
54
68
throw new Error ( `ApplicationRef instance not found` ) ;
55
69
}
0 commit comments