Why is the component in this simple plunk
@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 :)'
}
}
throwing:
EXCEPTION: Expression 'I'm {{message}} in App@0:5' has changed after it was checked. Previous value: 'I'm loading :( '. Current value: 'I'm all done loading :) ' in [I'm {{message}} in App@0:5]
when all I'm doing is updating a simple binding when my view is initiated?
For this I have tried above answers many does not work in latest version of Angular (6 or later)
I am using Material control that required changes after first binding done.
Adding my answer so, this helps some solve specific issue.
It throw an error because your code get updated when ngAfterViewInit() is called. Mean your initial value got changed when ngAfterViewInit take place, If you call that in ngAfterContentInit() then it will not throw an error.
I couldnt comment on @Biranchi s post since I dont have enough reputation, but it fixed the problem for me.
One thing to note! If adding changeDetection: ChangeDetectionStrategy.OnPush on the component didn't work, and its a child component (dumb component) try adding it to the parent also.
This fixed the bug, but I wonder what are the side effects of this.
As stated by drewmoore, the proper solution in this case is to manually trigger change detection for the current component. This is done using the
detectChanges()
method of theChangeDetectorRef
object (imported fromangular2/core
), or itsmarkForCheck()
method, which also makes any parent components update. Relevant example:Here are also Plunkers demonstrating the ngOnInit, setTimeout, and enableProdMode approaches just in case.
You can also put your call to updateMessage() in the ngOnInt()-Method, at least it works for me
In RC1 this does not trigger the exception
You just have to update your message in the right lifecycle hook, in this case is
ngAfterContentChecked
instead ofngAfterViewInit
, because in ngAfterViewInit a check for the variable message has been started but is not yet ended.see: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview
so the code will be just:
see the working demo on Plunker.