TIL, 2019-12-30
- What’s the difference between
markForCheck()
anddetectChanges()
? Reference- There is a case where any thing inside your model has changed but it hasn’t been reflected in the view, so need to notify Angular to detect those changes.
- It could be because the change detector is detached from the view.
- It could be because an update has happened but it hasn’t been inside the Angular Zone, and therefore Angular doesn’t know about it. If a third party function has updated your model and you want to update the view after that, you have to do something like this:
myFunction(){
someFunctionThatIsRunByAThirdPartyCode();
// Let's detect the changes that above function made to the model which Angular is not aware of.
this.cd.detectChanges();
}
- To make this function run inside the Angular change cycle, you can:
- Wrap it in the Angular zone (
this.zone.run(this.someFunctionThatIsRunByAThirdPartyCode)
) - Wrap the function inside a
setTimeout
:setTimeout(this.someFunctionThatIsRunByAThirdPartyCode)
- If you update the model after the change detection cycle is finished, you get this: “Expression has changed after it was checked”. This means that the model changed and then I ran my change detection to update the view, but there was another function in your code which updated the model again, and I don’t want to run CD again because there is no dirty checking like AngularJS anymore.
- Wrap it in the Angular zone (
- Proper way to fix: Make sure that update is inside the change detection cycle, do not update the model after that and move your code.
- Lazy way: Just make Angular run
detectChanges
. -
Put the code inside a
setTimeout
, becausesetTimeout
is patched by zone. markForCheck
: Run the change detection if any of these has happened:- One of the
@input
of the component has been completely replaced with a new value, or if the reference of the@Input
property has changed together. - If you don’t update the object reference, the change detection is not going to run, and the view will not reflect the update/mutation.
- An event has been fired and the child components emitted an event.
- One of the