markForCheck() and detectChanges()
detectChanges():void
If there is a case where anything inside the model has changed but it has not reflected in the view in this case you need to notify Angular to detect the changes and to update the view.
The cases for not detecting could be:
The Angular change detector is detached from the view or a change has happened but it hasn't been inside the Angular Zone so it doesn't know about it.
Let's see an example:
A third party function has updated your model and you want to update the changes in view.
theFunctionChangedByThirdPartyCode(){
model.text="new text";
}
The code is outside Angular's zone so you need to notify it to detect the changes and update the view.
function(){
theFunctionChangedByThirdPartyCode();
this.cd.detectChanges();
}
Their are other ways to do that but their is a possibility of getting "Expression has changed after it was checked" error.
To fix it :
Always make sure the change is inside the change detection cycle.
run detectChanges() after the change to make notify angular, but this is a lazy way.
markForCheck():void
markForCheck is needed when the ChangeDetectionStrategy of your component is OnPush which means only run the change detection if any of the below happens.
One of the @inputs of the component has been completely replaced with a new value.
var obj = {
name:'Milad'
};
you have to update the above to:
obj.name = "a new name";
This will not change or update the object reference so the change detection is not going to run so the view doesn't reflect the change. This means you have to manually tell Angular to update the view.
obj.name="a new name";
do this:
this.cd.markForCheck();
or this will make a change detection:
obj= {
name:"a new name"
};
Comments
0 comments
Please Sign in or Create an account to Post Comments