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

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

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


当前回答

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

ngOnInit() {
    this.updateMessage();
}

在RC1中,这不会触发异常

其他回答

在我的例子中,它发生在p-radioButton上。问题是,我使用的名称属性(这是不需要的)旁边的formControlName属性,就像这样:

<p-radioButton formControlName="isApplicant" name="isapplicant" value="T" label="Yes"></p-radioButton>
<p-radioButton formControlName="isApplicant" name="isapplicant" value="T" label="No"></p-radioButton>

我还将初始值“T”绑定到is申请人窗体控件,如下所示:

isApplicant: ["T"]

我通过删除单选按钮中的name属性来解决这个问题。 此外,因为2个单选按钮具有相同的值(T),这在我的情况下是错误的,简单地将其中一个值更改为另一个值(例如F)也解决了这个问题。

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

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

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

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

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

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

首先,请注意,这个异常只会在你以开发模式运行应用程序时被抛出(这是beta-0的默认情况):如果你在引导应用程序时调用enableProdMode(),它不会被抛出(参见updated plunk)。

其次,不要这样做,因为抛出这个异常是有充分理由的:简而言之,当处于开发模式时,每一轮更改检测之后都会立即进行第二轮,以验证自第一轮结束以来没有绑定发生更改,因为这将表明更改是由更改检测本身引起的。

在你的plunk中,绑定{{message}}是通过调用setMessage()来改变的,这发生在ngAfterViewInit钩子中,它作为初始变更检测回合的一部分发生。不过这本身并没有问题——问题是setMessage()改变了绑定,但不会触发新一轮的变更检测,这意味着直到在其他地方触发了未来的变更检测,才会检测到此更改。

结论:任何更改绑定的操作都需要触发一轮更改检测。

更新以回应所有关于如何做到这一点的例子的请求:@Tycho的解决方案是有效的,就像回答@MarkRajcok指出的三种方法一样。但坦率地说,我觉得他们都很丑陋,很错误,就像我们在ng1中习惯依赖的那种黑客一样。

可以肯定的是,在偶尔的情况下,这些hack是合适的,但如果您只是在非常偶然的基础上使用它们,这表明您正在与框架作斗争,而不是完全接受它的响应性。

恕我直言,更习惯的“Angular2方式”是这样的:(砰)

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

  ngAfterViewInit() {
    this.message.next('all done loading :)')
  }
}

简单:首先在你的组件结构中分离/移除变更检测,然后在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.
}