Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of ApplicationRef in Angular 2+?

Tags:

angular

I don't understand the ApplicationRef class and its uses. What does it mean to have a "reference to an Angular application running on a page"? When is this needed?

Please provide a small example using ApplicationRef.

like image 766
Bharat Chauhan Avatar asked Jun 16 '17 07:06

Bharat Chauhan


2 Answers

https://angular.io/api/core/ApplicationRef

  • allows to invoke application-wide change detection by calling appRef.tick()
  • it allows to add/remove views to be included in or excluded from change detection using attachView() and detachView()
  • provides a list of registered components and component types using componentTypes and components and some other change detection related information
like image 196
Günter Zöchbauer Avatar answered Oct 20 '22 23:10

Günter Zöchbauer


ApplicationRef contains reference to the root view and can be used to manually run change detection using tick function

Invoke this method to explicitly process change detection and its side-effects.

In development mode, tick() also performs a second change detection cycle to ensure that no further changes are detected. If additional changes are picked up during this second cycle, bindings in the app have side-effects that cannot be resolved in a single change detection pass. In this case, Angular throws an error, since an Angular application can only have one change detection pass during which all change detection must complete.

Here is an example:

@Component()
class C {
   property = 3;
   constructor(app: ApplicationRef, zone: NgZone) {
       // this emulates any third party code that runs outside Angular zone
       zone.runOutsideAngular(()=>{
          setTimeout(()=>{
             // this won't be reflected in the component view
             this.property = 5;

             // but if you run detection manually you will see the changes
             app.tick();
          })
       })

Another application is to attach a dynamically created component view for change detection if it was created using a root node:

  addDynamicComponent() {
     let factory = this.resolver.resolveComponentFactory(SimpleComponent);

     let newNode = document.createElement('div');
     newNode.id = 'placeholder';
     document.getElementById('container').appendChild(newNode);

     const ref = factory.create(this.injector, [], newNode);
     this.app.attachView(ref.hostView);
  }

check this answer for more details.

like image 34
Max Koretskyi Avatar answered Oct 20 '22 23:10

Max Koretskyi