Skip to content

Commit 79d3335

Browse files
committed
fix(helpers): add a way to set root view component ref
fixes #1056
1 parent b80c0b4 commit 79d3335

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

components/utils/components-helper.service.ts

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import { DOCUMENT } from '@angular/platform-browser';
1111
*/
1212
@Injectable()
1313
export class ComponentsHelper {
14+
public root:ViewContainerRef;
15+
1416
public constructor(private applicationRef:ApplicationRef,
1517
private componentFactoryResolver:ComponentFactoryResolver,
1618
private injector:Injector) {
@@ -21,25 +23,36 @@ export class ComponentsHelper {
2123
}
2224

2325
/**
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
2528
* to made this method working you need to add:
2629
* ```typescript
2730
* @Component({
2831
* selector: 'my-app',
2932
* ...
3033
* })
3134
* export class MyApp {
32-
* constructor(viewContainerRef: ViewContainerRef) {
35+
* constructor(componentsHelper:ComponentsHelper, viewContainerRef: ViewContainerRef) {
3336
* // A Default view container ref, usually the app root container ref.
3437
* // Has to be set manually until we can find a way to get it automatically.
35-
* this.viewContainerRef = viewContainerRef;
38+
* componentsHelper.setRootViewContainerRef(viewContainerRef)
3639
* }
3740
* }
3841
* ```
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
3948
* @returns {ViewContainerRef} - application root view component ref
4049
*/
4150
public getRootViewContainerRef():ViewContainerRef {
4251
// https://github.com/angular/angular/issues/9293
52+
if (this.root) {
53+
return this.root;
54+
}
55+
4356
const comps = this.applicationRef.components;
4457

4558
if(!comps.length) {
@@ -48,8 +61,9 @@ export class ComponentsHelper {
4861

4962
try {
5063
/* 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;
5367
} catch (e) {
5468
throw new Error(`ApplicationRef instance not found`);
5569
}

0 commit comments

Comments
 (0)