0

How can I access to root component for change properties?

Problem:

I have difference templates (default and for the custom page), and these templates have the different structure. I want the control to render process via the custom parameter in the class of root component (AppComponent).

As an example:

app.component.html:

<div>
    <div id="wrapper">
        <div *ngIf="!customPage">
            <div id="page-wrapper">
                <div class="container-fluid">
                    <router-outlet></router-outlet>
                </div>
            </div>
        </div>

        <div *ngIf="customPage">
            <router-outlet></router-outlet>
        </div>
    </div>
</div>

app.component.ts:

export class AppComponent{
    customPage: boolean;

    constructor() {
        this.customPage = false;
    }
}

And I try to access from custom.page.ts:

export class CustomComponent implements AfterViewChecked {
    constructor(private rootComponent: AppComponent) {
    }

    ngAfterViewChecked(): void {
        this.rootComponent.customPage = true;
    }
}

But I retrieve the error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

I try to use other lifecycle events, but on all events, I retrieve this error.

And, I think what this solution is not good. Maybe Angular2 have solutions for this problem?

Thank.

Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
ZhukV
  • 2,892
  • 6
  • 25
  • 36

1 Answers1

1

A simple way to avoid this error is to wait a tick, for example by using setTimeout.

setTimeout(() => this.rootComponent.customPage = true)
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
  • Yes, this works for me. But I think what angular should have the functionality for easy access to any component from runtime context. – ZhukV Aug 27 '17 at 18:44
  • but setTimeout is not a preferred way ever in angular, you can use it as alternate. – Pardeep Jain Aug 27 '17 at 18:49
  • 3
    You _do_ have an access to it. The error you're getting is because you're trying to change something during the process of Change Detection, which is what the error says. – Lazar Ljubenović Aug 27 '17 at 18:50
  • 1
    @PardeepJain Not a preferred way, but is sometimes the only way to do something. Indeed, not an ideal code but I'm sure very codebase has larger problems than one or two `setTimeout`s that do a single line of code. – Lazar Ljubenović Aug 27 '17 at 18:50