Search code examples
angulardependency-injectionangular2-changedetection

Angular: trigger change detection outside of angular dependency injection


Is it possible to trigger angular change detection globally, without injecting something like ApplicationRef? I would want to use the following functionality as a plain js function and not as a service method. Thus avoiding to inject an extra service whereever the function is needed.


export function frequentlyUsedUtilityFunction() {

  // ... do stuff

  // trigger change detection
  // get applicationRef or some similar mechanism
  const applicationRef = ...
  applicationRef.tick();

  // ... do more stuff
}

Solution

  • Not shure what I fully understand your question, but maybe this way can help you:

    1. Add code into AppComponent like this:
    constructor(private cdr: ChangeDetectorRef) {}
    
    public ngOnInit(): void {
      fromEvent(document, 'myEventToCdrTrigger').subscribe(() => {
        this.cdr.detectChanges();
      });
    }
    
    1. From your custom function:
    export function frequentlyUsedUtilityFunction() {
      const event = document.createEvent('Event');
      event.initEvent('myEventToCdrTrigger', true, true);
      document.dispatchEvent(event);
    }