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

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

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


当前回答

简单:首先在你的组件结构中分离/移除变更检测,然后在ngAfterViewInit()方法中启用detectChanges()

constructor(private cdr: ChangeDetectorRef) {
  this.cdr.detach() // detach/remove the change detection here in constructor
}


ngAfterViewInit(): void {
  // do load objects or other logics here
  
  // at the end of this method, call detectChanges() method.
  this.cdr.detectChanges(); // enable detectChanges here and you're done.
}

其他回答

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

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

你只需要在正确的生命周期钩子中更新你的消息,在这种情况下是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。

在使用数据表时,我得到了类似的错误。当你在另一个*ngFor数据表中使用*ngFor时,会在它拦截角度变化周期时抛出这个错误。因此,不要在数据表内部使用数据表,而是使用一个常规的表或替换mf。带有数组名的数据。这很好。

我从AfterViewInit切换到AfterContentChecked,它为我工作。

流程如下

在构造函数中添加依赖项: 构造函数(私有cdr: ChangeDetectorRef) {} 在实现方法代码中调用你的登录: ngAfterContentChecked () { this.cdr.detectChanges (); //调用或添加您的代码 }

你也可以使用rxjs Observable创建一个计时器。定时器功能,然后更新消息在您的订阅:           

Observable.timer(1).subscribe(()=> this.updateMessage());