为什么这个组件在这个简单的砰砰声中

@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]

当我所做的一切都是更新一个简单的绑定时,我的视图被启动?


当前回答

你不能用ngOnInit因为你只是改变了成员变量消息?

如果你想访问子组件@ViewChild(ChildComponent)的引用,你确实需要用ngAfterViewInit来等待它。

一个肮脏的修复方法是在下一个事件循环中调用updateMessage(),例如setTimeout。

ngAfterViewInit() {
  setTimeout(() => {
    this.updateMessage();
  }, 1);
}

其他回答

你也可以把你对updateMessage()的调用放在ngOnInt()-方法中,至少它对我有用

ngOnInit() {
    this.updateMessage();
}

在RC1中,这不会触发异常

我有几乎相同的案例,我有一系列的产品。我不得不让用户删除产品根据他们的选择。最后,如果数组中没有产品,那么我需要显示取消按钮而不是返回按钮,无需重新加载页面。

我通过检查ngAfterViewChecked()生命周期钩子中的空数组来完成。 这就是我是如何做到的,希望它有帮助:)

import { ChangeDetectorRef } from '@angular/core';

products: Product[];
someCondition: boolean;

constructor(private cdr: ChangeDetectorRef) {}

ngAfterViewChecked() {
  if(!this.someCondition) {
    this.emptyArray();
  }
}

emptyArray() {
    this.someCondition = this.products.length === 0 ? true : false;

    // run change detection explicitly
    this.cdr.detectChanges();
}

removeProduct(productId: number) {
    // your logic for removing product.
}

ngAfterViewChecked()为我工作:

import { Component, ChangeDetectorRef } from '@angular/core'; //import ChangeDetectorRef

constructor(private cdr: ChangeDetectorRef) { }
ngAfterViewChecked(){
   //your code to update the model
   this.cdr.detectChanges();
}

你只需要在正确的生命周期钩子中更新你的消息,在这种情况下是ngAfterContentChecked而不是ngAfterViewInit,因为在ngAfterViewInit中对变量消息的检查已经开始但还没有结束。

看到的: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html !# afterview

所以代码就是:

import { Component } from 'angular2/core'

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

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

查看工作演示在Plunker。

我有同样的错误,我可以通过使用AfterViewInit和ChangeDetectionStrategy来解决它。OnPush

这是一篇详细的文章。 https://medium.com/@bencabanes/angular-change-detection-strategy-an-introduction-819aaa7204e7