Could you please help me differentiate those two things.
According to my understanding, if you only work with observable, you can use detectChanges(). So you can change a component property directly or spy on a service call and return an observable, then you call detectChanges(), the changes will be available on html elements.
But for [(ngModel)] on input fields you need to call tick() for the changes to be render on html element.
So I'd it would be great if I know what they do and when to use what.
Thanks in advance.
The method detectChanges
is available on the ViewRef.
class ViewRef extends ChangeDetectorRef {
// inherited from core/ChangeDetectorRef
markForCheck(): void <-----------------------------
detach(): void
detectChanges(): void
checkNoChanges(): void
reattach(): void
}
ViewRef
is an underlying representation of a component. When writing tests instead of ViewRef
another abstraction is introduced which is fixture
:
fixture = TestBed.createComponent(BannerComponent);
It wraps the component similar to ViewRef
.
detectChanges
method runs change detection for the underlying component and performs the following operations:
and many others.
To learn more you can read Everything you need to know about change detection in Angular. So in order to validate changes in the DOM or validate input bindings you need to run detectChanges
.
Angular docs describe it pretty well:
The tick function is one of the Angular testing utilities and a companion to fakeAsync. You can only call it within a fakeAsync body.
Calling tick() simulates the passage of time until all pending asynchronous activities finish, including the resolution of the getQuote promise in this test case.
With ngModel
you need to call it because the control that is created inside ngModel
is registered asynchonously. Here is the quote from the article by Victor Savkin on forms:
To make it work, NgModel doesn’t add a form control synchronously — it does it in a microtask. In the example above, the three ngModels will schedule three microtasks to add the speaker, title, and highRating controls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With