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
.
https://angular.io/api/core/ApplicationRef
appRef.tick()
attachView()
and detachView()
componentTypes
and components
and some other change detection related informationApplicationRef
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.
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