2017-11-20 21 views
0

私は親と子の間でデータを渡すためにサービスを使用しています。目的は、子の読み込みに応じて親のUIに子の固有情報を更新することです。ExpressionChangedAfterItHasBeenCheckedError。角2(5)* ngIf

サービス:

import { Subject } from "rxjs/Subject"; 

export class ChildDataService { 
    private childDetails = new Subject<{}>(); 

    childLoaded$ = this.childDetails.asObservable(); 
    changedComponentName(option: {}){ 
    this.childDetails.next(option); 
    } 
} 

親コンポーネント:

import { Component, OnInit, ViewEncapsulation } from '@angular/core'; 
import { ChildDataService } from "../core/helpers/child-data.service"; 
import { Subscription } from "rxjs/Subscription"; 

@Component({ 
    selector: 'app-parent', 
    templateUrl: './parent.component.html', 
    styleUrls: ['./parent.component.scss'], 
    encapsulation: ViewEncapsulation.None 
}) 
export class ParentComponent implements OnInit { 
    childDetails: {title?: string}; 

    private subscription:Subscription; 

    constructor(private childDataService: ChildDataService) { 
    this.childDataService.childLoaded$.subscribe(
     newChildDetails => { 
     console.log(newChildDetails); 
     this.childDetails = newChildDetails 
     }); 
    } 
} 

例チャイルドコンポーネント:

import { Component, OnInit, ViewEncapsulation } from '@angular/core'; 
import { ChildDataService } from "../../core/helpers/child-data.service"; 

@Component({ 
    selector: 'app-child-dashboard', 
    templateUrl: './child-dashboard.component.html', 
    styleUrls: ['./child-dashboard.component.scss'], 
    encapsulation: ViewEncapsulation.None 
}) 
export class ChildDashboardComponent implements OnInit { 

    constructor(private childDataService: ChildDataService) { } 

    public ngOnInit() { 
    this.childDataService.changedComponentName({ 
     title: 'Dashboard' 
    }); 
    } 
} 

親HTML:

<div class="subheader"> 
    <h1>{{ childDetails?.title }}</h1> 
    <button *ngIf="childDetails?.title == 'Dashboard'">dashboard</button> 
    <button *ngIf="childDetails?.title == 'SecondChild'">Second Child</button> 
</div> 

この設定では、routerLinkをクリックするとエラー "ExpressionChangedAfterItHasBeenCheckedError"が表示されます。同じリンクをもう一度クリックすると、エラーは持続しますが、正しいボタンが表示されます。週末はこれでどこにも行けないので、どんな助けでも大歓迎です。

答えて

0
public ngOnInit() { 
    setTimeout(() => { 
     this.childDataService.changedComponentName({ 
      title: 'Dashboard' 
     }), {}); 
} 

これは機能するはずです。

async ngOnInit() { 
    await this.childDataService.changedComponentName({ 
      title: 'Dashboard' 
     }); 
} 
+0

私の実験の過程でこれを試していたか、それと同様でした。残念ながら、それは効果がありません。 – Cheekumz

+0

編集済み回答..これを試してみてください。問題は、コンポーネントレンダリングの前にページがロードされていることです。 'ngAfterViewInit'も試しましたか? –

+0

は、 'ngAfterViewInit'について聞いたことがありませんが、読んだ後は確かに正しい方向に進んでいるようです。乾杯、進行状況を更新します。 – Cheekumz

関連する問題