Skip to content

Commit

Permalink
fix(core): Angular should not ignore changes that happen outside the …
Browse files Browse the repository at this point in the history
…zone

When Angular receives a clear indication that change detection should
run again, this should not be ignored, regardless of what Zone it
happened in. This change updates the default change detection scheduling
approach of Zone-based applications to ensure a change detection will
run when these events happen outside the Angular zone (which includes,
for example, updating a signal that's read in a template, setting an
input of a `ComponentRef`, attaching a view marked for check, calling
`ChangeDetectorRef.markForCheck`, etc.).

This does not apply to applications using `NoopNgZone` or those which
have a custom `NgZone` implementation without ZoneJS.

The impact of this change will most often be seen in existing unit tests. Tests
execute outside the Angular Zone and this can mean that state in the
test is not fully recognized by Angular. Now that Angular will ensure
change detection _does_ run, even when the state update originates from
outside the zone, tests may observe additional rounds of change
detection compared to the previous behavior. Often, this should be seen
as more correct and the test should be updated, but in cases where it is
too much effort to debug, the test can revert to the old behavior by adding
`provideZoneChangeDetection({schedulingMode: NgZoneSchedulingMode.NgZoneOnly})`
to the `TestBed` providers.

fixes #55238
fixes #53844
fixes #53841
fixes #52610
fixes #53566
fixes #52940
fixes #51970
fixes #51768
fixes #50702
fixes #50259
fixes #50266
fixes #50160
fixes #49940
fixes #49398
fixes #48890
fixes #48608
fixes #45105
fixes #42241
fixes #41553
fixes #37223
fixes #37062
fixes #35579
fixes #31695
fixes #24728
fixes #23697
fixes #19814
fixes #13957
fixes #11565
fixes #15770
fixes #15946
fixes #18254
fixes #19731
fixes #20112
fixes #22472
fixes #23697
fixes #24727
fixes #47236

BREAKING CHANGE:

Angular will ensure change detection runs, even when the state update originates from
outside the zone, tests may observe additional rounds of change
detection compared to the previous behavior.

This change will be more likely to impact existing unit tests.
This should usually be seen as more correct and the test should be updated,
but in cases where it is too much effort to debug, the test can revert to the old behavior by adding
`provideZoneChangeDetection({schedulingMode: NgZoneSchedulingMode.NgZoneOnly})`
to the `TestBed` providers.

Similarly, applications which may want to update state outside the zone
and _not_ trigger change detection can add
`provideZoneChangeDetection({schedulingMode: NgZoneSchedulingMode.NgZoneOnly})`
to the providers in `bootstrapApplication` or add
`schedulingMode: NgZoneSchedulingMode.NgZoneOnly` to the
`BootstrapOptions` of `bootstrapModule`.
  • Loading branch information
atscott committed Apr 16, 2024
1 parent e6425f7 commit 3f48dab
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 21 deletions.
10 changes: 10 additions & 0 deletions packages/core/src/change_detection/scheduling/flags.ts
@@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

/** Flag to enable/disable the zoneless scheduler as default provider with zone scheduling. */
export const alwaysProvideZonelessScheduler = true;
Expand Up @@ -17,6 +17,7 @@ import {performanceMarkFeature} from '../../util/performance';
import {NgZone} from '../../zone';
import {InternalNgZoneOptions} from '../../zone/ng_zone';

import {alwaysProvideZonelessScheduler} from './flags';
import {ChangeDetectionScheduler, ZONELESS_SCHEDULER_DISABLED} from './zoneless_scheduling';
import {ChangeDetectionSchedulerImpl} from './zoneless_scheduling_impl';

Expand Down Expand Up @@ -93,10 +94,12 @@ export function internalProvideZoneChangeDetection(
}
},
{provide: INTERNAL_APPLICATION_ERROR_HANDLER, useFactory: ngZoneApplicationErrorHandlerFactory},
// Always disable scheduler whenever explicitly disabled, even if Hybrid was specified elsewhere
// Always disable scheduler whenever explicitly disabled, even if another place called
// `provideZoneChangeDetection` without the 'ignore' option.
ignoreChangesOutsideZone === true ? {provide: ZONELESS_SCHEDULER_DISABLED, useValue: true} : [],
// Only provide scheduler when explicitly not disabled
ignoreChangesOutsideZone === false ?
// TODO(atscott): This should move to the same places that zone change detection is provided by
// default instead of being in the zone scheduling providers.
alwaysProvideZonelessScheduler || ignoreChangesOutsideZone === false ?
{provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl} :
[],
];
Expand Down
3 changes: 2 additions & 1 deletion packages/core/test/application_ref_spec.ts
Expand Up @@ -8,7 +8,7 @@

import {DOCUMENT, ɵgetDOM as getDOM} from '@angular/common';
import {ResourceLoader} from '@angular/compiler';
import {APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, ChangeDetectionStrategy, Compiler, CompilerFactory, Component, EnvironmentInjector, InjectionToken, LOCALE_ID, NgModule, NgZone, PlatformRef, RendererFactory2, TemplateRef, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, ChangeDetectionStrategy, Compiler, CompilerFactory, Component, EnvironmentInjector, InjectionToken, LOCALE_ID, NgModule, NgZone, PlatformRef, provideZoneChangeDetection, RendererFactory2, TemplateRef, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {ErrorHandler} from '@angular/core/src/error_handler';
import {ComponentRef} from '@angular/core/src/linker/component_factory';
import {createEnvironmentInjector, getLocaleId} from '@angular/core/src/render3';
Expand Down Expand Up @@ -771,6 +771,7 @@ describe('AppRef', () => {
beforeEach(() => {
stableCalled = false;
TestBed.configureTestingModule({
providers: [provideZoneChangeDetection({ignoreChangesOutsideZone: true})],
declarations: [
SyncComp, MicroTaskComp, MacroTaskComp, MicroMacroTaskComp, MacroMicroTaskComp, ClickComp
],
Expand Down
3 changes: 3 additions & 0 deletions packages/core/test/bundling/defer/bundle.golden_symbols.json
Expand Up @@ -1370,6 +1370,9 @@
{
"name": "init_fields"
},
{
"name": "init_flags"
},
{
"name": "init_forward_ref"
},
Expand Down
6 changes: 3 additions & 3 deletions packages/core/test/change_detection_scheduler_spec.ts
Expand Up @@ -574,7 +574,9 @@ describe('Angular with scheduler and ZoneJS', () => {
{providers: [{provide: ComponentFixtureAutoDetect, useValue: true}]});
});

it('current default behavior requires updates inside Angular zone', async () => {
it('requires updates inside Angular zone when using ngZoneOnly', async () => {
TestBed.configureTestingModule(
{providers: [provideZoneChangeDetection({ignoreChangesOutsideZone: true})]});
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
Expand All @@ -593,8 +595,6 @@ describe('Angular with scheduler and ZoneJS', () => {
});

it('updating signal outside of zone still schedules update when in hybrid mode', async () => {
TestBed.configureTestingModule(
{providers: [provideZoneChangeDetection({ignoreChangesOutsideZone: false})]});
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
Expand Down
12 changes: 0 additions & 12 deletions packages/router/src/router.ts
Expand Up @@ -10,7 +10,6 @@ import {Location} from '@angular/common';
import {
inject,
Injectable,
NgZone,
Type,
ɵConsole as Console,
ɵPendingTasks as PendingTasks,
Expand Down Expand Up @@ -106,7 +105,6 @@ export class Router {
}
private disposed = false;
private nonRouterCurrentEntryChangeSubscription?: SubscriptionLike;
private isNgZoneEnabled = false;

private readonly console = inject(Console);
private readonly stateManager = inject(StateManager);
Expand Down Expand Up @@ -186,8 +184,6 @@ export class Router {
readonly componentInputBindingEnabled: boolean = !!inject(INPUT_BINDER, {optional: true});

constructor() {
this.isNgZoneEnabled = inject(NgZone) instanceof NgZone && NgZone.isInAngularZone();

this.resetConfig(this.config);

this.navigationTransitions
Expand Down Expand Up @@ -522,14 +518,6 @@ export class Router {
skipLocationChange: false,
},
): Promise<boolean> {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (this.isNgZoneEnabled && !NgZone.isInAngularZone()) {
this.console.warn(
`Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?`,
);
}
}

const urlTree = isUrlTree(url) ? url : this.parseUrl(url);
const mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);

Expand Down
10 changes: 8 additions & 2 deletions packages/service-worker/test/provider_spec.ts
Expand Up @@ -166,7 +166,10 @@ const serviceWorkerModuleApi = 'ServiceWorkerModule';
TestBed.configureTestingModule({
providers: [
provideServiceWorker('sw.js'),
{provide: ApplicationRef, useValue: {isStable: isStableSub.asObservable()}},
{
provide: ApplicationRef,
useValue: {isStable: isStableSub.asObservable(), afterTick: new Subject()},
},
{provide: PLATFORM_ID, useValue: 'browser'},
{
provide: SwRegistrationOptions,
Expand All @@ -178,7 +181,10 @@ const serviceWorkerModuleApi = 'ServiceWorkerModule';
TestBed.configureTestingModule({
imports: [ServiceWorkerModule.register('sw.js')],
providers: [
{provide: ApplicationRef, useValue: {isStable: isStableSub.asObservable()}},
{
provide: ApplicationRef,
useValue: {isStable: isStableSub.asObservable(), afterTick: new Subject()},
},
{provide: PLATFORM_ID, useValue: 'browser'},
{
provide: SwRegistrationOptions,
Expand Down

0 comments on commit 3f48dab

Please sign in to comment.