式___はチェック後に変更されました 質問する

式___はチェック後に変更されました 質問する

なぜこの単純なコンポーネントはドンドン

@Component({
  selector: 'my-app',
  template: `<div>I'm {{message}} </div>`,
})
export class App {
  message:string = 'loading :(';

  ngAfterViewInit() {
    this.updateMessage();
  }

  updateMessage(){
    this.message = 'all done loading :)'
  }
}

投げ:

例外: 式 'I'm {{message}} in App@0:5' はチェック後に変更されました。以前の値: 'I'm loading :( '。現在の値: 'I'm all done loading :) ' in [I'm {{message}} in App@0:5]

私がやっていることは、ビューが初期化されたときに単純なバインディングを更新することだけですか?

ベストアンサー1

drewmoore が述べたように、この場合の適切な解決策は、現在のコンポーネントの変更検出を手動でトリガーすることです。これは、オブジェクトdetectChanges()のメソッドChangeDetectorRef( からインポートangular2/core) またはそのmarkForCheck()メソッドを使用して行われ、これにより親コンポーネントも更新されます。:

import { Component, ChangeDetectorRef, AfterViewInit } from 'angular2/core'

@Component({
  selector: 'my-app',
  template: `<div>I'm {{message}} </div>`,
})
export class App implements AfterViewInit {
  message: string = 'loading :(';

  constructor(private cdr: ChangeDetectorRef) {}

  ngAfterViewInit() {
    this.message = 'all done loading :)'
    this.cdr.detectChanges();
  }

}

こちらもPlunkersが実演していますngOnInitタイムアウトの設定、 そして有効にする念のためアプローチします。

おすすめ記事