2017-08-27 94 views
0

如何訪問根組件以獲取更改屬性?角度4:訪問根組件

問題:

我有差異的模板(默認和自定義頁面),而這些模板具有不同的結構。我希望控件通過根組件(AppComponent)類中的自定義參數呈現過程。

舉個例子:

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; 
    } 
} 

我試着從自定義訪問.page.ts:

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

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

不過我檢索錯誤:

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

我嘗試使用其他生命週期事件,但在所有的事件,我檢索此錯誤。

而且,我覺得這個解決方案不好。也許Angular2爲這個問題提供瞭解決方案?

謝謝。

+0

的可能的複製[角2 - 共享服務在加載](https://stackoverflow.com/questions/45443908/angular-2-share-service-on-load) –

+0

可以使用'[隱藏]'而不是'* ngIf' –

回答

0

避免此錯誤的一種簡單方法是等待打勾,例如通過使用setTimeout

setTimeout(() => this.rootComponent.customPage = true) 
+0

是的,這對我很有用。但我認爲角度應該具有從運行環境中輕鬆訪問任何組件的功能。 – ZhukV

+0

但setTimeout並不是有角度的首選方式,您可以將它用作備用。 –

+2

您_do_有權訪問它。你得到的錯誤是因爲你正在嘗試在變更檢測過程中改變某些東西,這就是錯誤所說的。 –