First of all what is ApplicationRef?
Application Ref contains reference to the root view and can be used to
manually run change detection using tick function.
So how do we use the tick()
function?
Inject it into your component constructor and use it as you wish!
N.B. I purposely entered the ChangeDetectionStrategy.OnPush to remove the automatic update, so we should force the application to update manually.
In this regard we will use Tick()
function !
SIMPLE TEST CASE:
component.ts
@Component ({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
...
counter = 1;
constructor (private appRef: ApplicationRef) {
setInterval (() => this.counter ++, 1000);
}
updateApplication () {
this.appRef.tick ();
}
}
component.html
<h1>{{counter}}</h1>
<button (click)="updateApplication()"> UPDATE APP </button>
In my example every time we click on the UPDATE APP button we call the tick()
function which updates every single child component starting from the application root.
So in our case it will simply update the counter variable.
Stackblitz Test Case
As for your second question, if you can avoid having the tick()
called twice in devMode
the answer is You can't avoid it!
But I don't think this behavior leads to a recursive call, most likely you have used the function incorrectly, grafting components that call the tick()
or not disabling the changeDetection so as to start two or more changeDetects together.