Skip to content

Commit be58dba

Browse files
committed
refactor(core): newly created and any dirty views should get refreshed during CD (#53022)
When a view has the `Dirty` flag and is reattached, we should ensure that it is reached and refreshed during the next change detection run from above. In addition, when a view is created and attached, we should ensure that it is reached and refreshed during change detection. This can happen if the view is created and attached outside a change run or when it is created and attached after its insertion view was already checked. In both cases, we should ensure that the view is reached and refreshed during either the current change detection or the next one (if change detection is not already running). We can achieve this by creating all views with the `Dirty` flag set. However, this does happen to be a breaking change in some scenarios. The one identified internally was actually depending on change detection _not_ running immediately because it relied on an input value that was set using `ngModel`. Because `ngModel` sets its value in a `Promise`, it is not available until the _next_ change detection cycle. Ensuring created views run in the current change change detection will result in different behavior in this case. Making option the default is the solution to #52928. That will have to wait for a major version. PR Close #53022
1 parent 203a3d5 commit be58dba

12 files changed

Lines changed: 87 additions & 33 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
// TODO(atscott): flip default internally ASAP and externally for v18 (#52928)
10+
let _ensureDirtyViewsAreAlwaysReachable = false;
11+
12+
export function getEnsureDirtyViewsAreAlwaysReachable() {
13+
return _ensureDirtyViewsAreAlwaysReachable;
14+
}
15+
export function setEnsureDirtyViewsAreAlwaysReachable(v: boolean) {
16+
_ensureDirtyViewsAreAlwaysReachable = v;
17+
}

‎packages/core/src/core_private_export.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export {whenStable as ɵwhenStable} from './application/application_ref';
1111
export {IMAGE_CONFIG as ɵIMAGE_CONFIG, IMAGE_CONFIG_DEFAULTS as ɵIMAGE_CONFIG_DEFAULTS, ImageConfig as ɵImageConfig} from './application/application_tokens';
1212
export {internalCreateApplication as ɵinternalCreateApplication} from './application/create_application';
1313
export {defaultIterableDiffers as ɵdefaultIterableDiffers, defaultKeyValueDiffers as ɵdefaultKeyValueDiffers} from './change_detection/change_detection';
14+
export {getEnsureDirtyViewsAreAlwaysReachable as ɵgetEnsureDirtyViewsAreAlwaysReachable, setEnsureDirtyViewsAreAlwaysReachable as ɵsetEnsureDirtyViewsAreAlwaysReachable} from './change_detection/flags';
1415
export {Console as ɵConsole} from './console';
1516
export {DeferBlockDetails as ɵDeferBlockDetails, getDeferBlocks as ɵgetDeferBlocks} from './defer/discovery';
1617
export {renderDeferBlockState as ɵrenderDeferBlockState, triggerResourceLoading as ɵtriggerResourceLoading} from './defer/instructions';

‎packages/core/src/render3/component_ref.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -220,12 +220,12 @@ export class ComponentFactory<T> extends AbstractComponentFactory<T> {
220220
hostRenderer, rootSelectorOrNode, this.componentDef.encapsulation, rootViewInjector) :
221221
createElementNode(hostRenderer, elementName, getNamespace(elementName));
222222

223-
// Signal components use the granular "RefreshView" for change detection
224-
const signalFlags = (LViewFlags.SignalView | LViewFlags.IsRoot);
225-
// Non-signal components use the traditional "CheckAlways or OnPush/Dirty" change detection
226-
const nonSignalFlags = this.componentDef.onPush ? LViewFlags.Dirty | LViewFlags.IsRoot :
227-
LViewFlags.CheckAlways | LViewFlags.IsRoot;
228-
const rootFlags = this.componentDef.signals ? signalFlags : nonSignalFlags;
223+
let rootFlags = LViewFlags.IsRoot;
224+
if (this.componentDef.signals) {
225+
rootFlags |= LViewFlags.SignalView;
226+
} else if (!this.componentDef.onPush) {
227+
rootFlags |= LViewFlags.CheckAlways;
228+
}
229229

230230
let hydrationInfo: DehydratedView|null = null;
231231
if (hostRNode !== null) {

‎packages/core/src/render3/instructions/shared.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,8 @@ export function createLView<T>(
9494
hydrationInfo: DehydratedView|null): LView<T> {
9595
const lView = tView.blueprint.slice() as LView;
9696
lView[HOST] = host;
97-
lView[FLAGS] = flags | LViewFlags.CreationMode | LViewFlags.Attached | LViewFlags.FirstLViewPass;
97+
lView[FLAGS] = flags | LViewFlags.CreationMode | LViewFlags.Attached | LViewFlags.FirstLViewPass |
98+
LViewFlags.Dirty;
9899
if (embeddedViewInjector !== null ||
99100
(parentLView && (parentLView[FLAGS] & LViewFlags.HasEmbeddedViewInjector))) {
100101
lView[FLAGS] |= LViewFlags.HasEmbeddedViewInjector;

‎packages/core/src/render3/util/view_utils.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9+
import {getEnsureDirtyViewsAreAlwaysReachable} from '../../change_detection/flags';
910
import {RuntimeError, RuntimeErrorCode} from '../../errors';
1011
import {assertDefined, assertGreaterThan, assertGreaterThanOrEqual, assertIndexInRange, assertLessThan} from '../../util/assert';
1112
import {assertTNode, assertTNodeForLView} from '../assert';
@@ -206,6 +207,12 @@ export function requiresRefreshOrTraversal(lView: LView) {
206207
* parents above.
207208
*/
208209
export function updateAncestorTraversalFlagsOnAttach(lView: LView) {
210+
// When we attach a view that's marked `Dirty`, we should ensure that it is reached during the
211+
// next CD traversal so we add the `RefreshView` flag and mark ancestors accordingly.
212+
if (lView[FLAGS] & LViewFlags.Dirty && getEnsureDirtyViewsAreAlwaysReachable()) {
213+
lView[FLAGS] |= LViewFlags.RefreshView;
214+
}
215+
209216
if (!requiresRefreshOrTraversal(lView)) {
210217
return;
211218
}

‎packages/core/test/acceptance/change_detection_spec.ts‎

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99

1010
import {CommonModule} from '@angular/common';
11-
import {ApplicationRef, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentRef, createComponent, Directive, DoCheck, EmbeddedViewRef, ErrorHandler, EventEmitter, inject, Input, NgModule, OnInit, Output, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef} from '@angular/core';
11+
import {ApplicationRef, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentRef, Directive, DoCheck, EmbeddedViewRef, ErrorHandler, EventEmitter, inject, Input, NgModule, OnInit, Output, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef, ɵgetEnsureDirtyViewsAreAlwaysReachable, ɵsetEnsureDirtyViewsAreAlwaysReachable} from '@angular/core';
1212
import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
1313
import {expect} from '@angular/platform-browser/testing/src/matchers';
1414
import {BehaviorSubject} from 'rxjs';
@@ -184,57 +184,68 @@ describe('change detection', () => {
184184

185185
describe('markForCheck', () => {
186186
it('should mark OnPush ancestor of dynamically created component views as dirty', () => {
187+
const previous = ɵgetEnsureDirtyViewsAreAlwaysReachable();
188+
ɵsetEnsureDirtyViewsAreAlwaysReachable(true);
187189
@Component({
188190
selector: `test-cmpt`,
189191
template: `{{counter}}|<ng-template #vc></ng-template>`,
190-
changeDetection: ChangeDetectionStrategy.OnPush
192+
changeDetection: ChangeDetectionStrategy.OnPush,
193+
standalone: true,
191194
})
192195
class TestCmpt {
193196
counter = 0;
194197
@ViewChild('vc', {read: ViewContainerRef}) vcRef!: ViewContainerRef;
195198

196-
constructor() {}
197-
198199
createComponentView<T>(cmptType: Type<T>): ComponentRef<T> {
199200
return this.vcRef.createComponent(cmptType);
200201
}
201202
}
202203

203204
@Component({
204205
selector: 'dynamic-cmpt',
205-
template: `dynamic`,
206+
template: `dynamic|{{binding}}`,
207+
standalone: true,
206208
changeDetection: ChangeDetectionStrategy.OnPush
207209
})
208210
class DynamicCmpt {
211+
@Input() binding = 'binding';
209212
}
210213

211-
@NgModule({declarations: [DynamicCmpt]})
212-
class DynamicModule {
213-
}
214-
215-
TestBed.configureTestingModule({imports: [DynamicModule], declarations: [TestCmpt]});
216-
217214
const fixture = TestBed.createComponent(TestCmpt);
218215

219216
// initial CD to have query results
220217
// NOTE: we call change detection without checkNoChanges to have clearer picture
221218
fixture.detectChanges(false);
222219
expect(fixture.nativeElement).toHaveText('0|');
223220

224-
// insert a dynamic component
221+
// insert a dynamic component, but do not specifically mark parent dirty
222+
// (dynamic components with OnPush flag are created with the `Dirty` flag)
225223
const dynamicCmptRef = fixture.componentInstance.createComponentView(DynamicCmpt);
226224
fixture.detectChanges(false);
227-
expect(fixture.nativeElement).toHaveText('0|dynamic');
225+
expect(fixture.nativeElement).toHaveText('0|dynamic|binding');
228226

229227
// update model in the OnPush component - should not update UI
230228
fixture.componentInstance.counter = 1;
231229
fixture.detectChanges(false);
232-
expect(fixture.nativeElement).toHaveText('0|dynamic');
230+
expect(fixture.nativeElement).toHaveText('0|dynamic|binding');
233231

234232
// now mark the dynamically inserted component as dirty
235233
dynamicCmptRef.changeDetectorRef.markForCheck();
236234
fixture.detectChanges(false);
237-
expect(fixture.nativeElement).toHaveText('1|dynamic');
235+
expect(fixture.nativeElement).toHaveText('1|dynamic|binding');
236+
237+
// Update, mark for check, and detach before change detection, should not update
238+
dynamicCmptRef.setInput('binding', 'updatedBinding');
239+
dynamicCmptRef.changeDetectorRef.markForCheck();
240+
dynamicCmptRef.changeDetectorRef.detach();
241+
fixture.detectChanges(false);
242+
expect(fixture.nativeElement).toHaveText('1|dynamic|binding');
243+
244+
// reattaching and run CD from the top should update
245+
dynamicCmptRef.changeDetectorRef.reattach();
246+
fixture.detectChanges(false);
247+
expect(fixture.nativeElement).toHaveText('1|dynamic|updatedBinding');
248+
ɵsetEnsureDirtyViewsAreAlwaysReachable(previous);
238249
});
239250

240251
it('should support re-enterant change detection', () => {

‎packages/core/test/bundling/defer/bundle.golden_symbols.json‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,9 @@
533533
{
534534
"name": "_enable_super_gross_mode_that_will_cause_bad_things"
535535
},
536+
{
537+
"name": "_ensureDirtyViewsAreAlwaysReachable"
538+
},
536539
{
537540
"name": "_findMatchingDehydratedViewImpl"
538541
},
@@ -1331,6 +1334,9 @@
13311334
{
13321335
"name": "init_fields"
13331336
},
1337+
{
1338+
"name": "init_flags"
1339+
},
13341340
{
13351341
"name": "init_forward_ref"
13361342
},

‎packages/core/test/bundling/forms_reactive/bundle.golden_symbols.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,9 @@
638638
{
639639
"name": "_enable_super_gross_mode_that_will_cause_bad_things"
640640
},
641+
{
642+
"name": "_ensureDirtyViewsAreAlwaysReachable"
643+
},
641644
{
642645
"name": "_getInsertInFrontOfRNodeWithI18n"
643646
},

‎packages/core/test/bundling/forms_template_driven/bundle.golden_symbols.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,9 @@
629629
{
630630
"name": "_enable_super_gross_mode_that_will_cause_bad_things"
631631
},
632+
{
633+
"name": "_ensureDirtyViewsAreAlwaysReachable"
634+
},
632635
{
633636
"name": "_getInsertInFrontOfRNodeWithI18n"
634637
},

‎packages/core/test/bundling/router/bundle.golden_symbols.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,9 @@
854854
{
855855
"name": "_enable_super_gross_mode_that_will_cause_bad_things"
856856
},
857+
{
858+
"name": "_ensureDirtyViewsAreAlwaysReachable"
859+
},
857860
{
858861
"name": "_getInsertInFrontOfRNodeWithI18n"
859862
},

0 commit comments

Comments
 (0)