0

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
}

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your approach is a nice idea. It broght me to another idea. If you run a setTimeout(() => {}, 0) in the utility function it should also trigger change detection (async action). However not tested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.