Skip to content

Allow view creation during change detection #15634

Closed

Description

@pkozlowski-opensource

I'm submitting a ... (check one with "x")

[x] bug report => search github for a similar issue or PR before submitting

Current behavior

Creating dynamically a new view from a lifecycle hook (ex.: ngOnInit) will result in the following error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'xxx'. Current value: 'yyy'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?

Expected behavior

Dynamically created views should be change detected "inline" if possible (as right now), but if we cannot do this, we should change detect them at then end of the current run, and not throw the mentioned error.

Minimal reproduction of the problem with instructions

https://plnkr.co/edit/uh4oxxA3Yq6i45SA52SS?p=preview

What is the motivation / use case for changing the behavior?

There are legitimate use-cases where a new view needs to be created from a lifecycle hook, ex.: opening a modal window from the ngOnInit lifecycle hook. This was initially reported on ng-bootstrap side via ng-bootstrap/ng-bootstrap#1159

The pb was discussed with @tbosch and the issue is opened as the result of this discussion.

  • Angular version:

2.3.x, 4.0.X

  • Browser:

all

  • Language:

all

Activity

  1. squadwuschel commented on Jun 12, 2017

    @squadwuschel

    Its a strange behavior and a fix would be really nice, because with this problem the modal from ng-bootstrap is not useable.

  2. tytskyi commented on Jun 12, 2017

    @tytskyi
  3. victornoel commented on Jul 16, 2017

    @victornoel
    Contributor

    @tytskyi yes, that's an acceptable workaround, as well as using setTimeout() too.

    I have the same problem when opening material2 dialogs from within an observable chain (the dialog is opened and closed when some conditions are verified in the ngrx store).

  4. Martin-Luft commented on Jul 17, 2017

    @Martin-Luft

    The same problem was reported here: #17572 (comment)

  5. dgroh commented on Jul 24, 2017

    @dgroh

    This is also happening when having nested router-outlets and using subscribe to watch for changes in the child outlet, for example:

      <div class="component-wrapper">
        <div *ngIf="!spinner.visible">
          <router-outlet></router-outlet> <!--This is the parent outlet-->
        </div>
        <app-spinner #spinner></app-spinner>
      </div>

    that is my SpinnerComponent:

    @Component({
      selector: "app-spinner",
      templateUrl: "./spinner.component.html",
      styleUrls: ["./spinner.component.scss"]
    })
    export class SpinnerComponent  implements OnInit, OnDestroy {
    
      public visible = true;
    
      private subscription: Subscription;
    
      constructor(
        private loaderService: LoaderService
      ) { }
    
      public ngOnInit() {
        this.subscription = this.loaderService.loaderState
          .subscribe((state: LoaderState) => {
            this.visible = state.show;
          });
      }
    
      public ngOnDestroy() {
        this.subscription.unsubscribe();
      }
    }

    I tried to wrap the subscription in a setTimeout, but it still didn't work.

  6. maxisam commented on Jul 25, 2017

    @maxisam
    Contributor

    @dgroh You can subscribe to Router.event and use start and end event to turn on and off the spinner.

  7. wulfsberg commented on Aug 1, 2017

    @wulfsberg

    I have a situation where the app and a component are both injecting a shared trackerService.
    This service has an Observable value which the app subscribes to with an |async pipe.

    The ngOnChanges/ngOnInit in the component causes an operation which emits a new value on the Observable.

    This currently causes an ExpressionChangedAfterItHasBeenCheckedError, since the Observable has been resolved and shown in the app template(*) before the component is instantiated and triggers an emit.

    Is a case like this covered under this issue?

    (*) Simply writing the value with {{trackerService.count|async}} does not cause an exception, but doesn't update, while doing <div [ngClass]="{shown: trackerService.count|async}"> throws the exception.

  8. 53 remaining items

  9. petebacondarwin commented on Nov 9, 2020

    @petebacondarwin
    Contributor

    Possibly this can be solved via markDirty()... see

    /**
    * Marks the component as dirty (needing change detection). Marking a component dirty will
    * schedule a change detection on it at some point in the future.
    *
    * Marking an already dirty component as dirty won't do anything. Only one outstanding change
    * detection can be scheduled per component tree.
    *
    * @param component Component to mark as dirty.
    */
    export function markDirty(component: {}): void {
    ngDevMode && assertDefined(component, 'component');
    const rootView = markViewDirty(getComponentViewByInstance(component))!;
    ngDevMode && assertDefined(rootView[CONTEXT], 'rootContext should be defined');
    scheduleTick(rootView[CONTEXT] as RootContext, RootContextFlags.DetectChanges);
    }

  10. sheikhziadahmed commented on Jun 9, 2021

    @sheikhziadahmed

    Any updates on this one? Its mid of 2021.

  11. all2pie commented on Aug 23, 2021

    @all2pie

    Getting the same issue in my Directive

    export class MyDirective implements Validator {
      
      constructor(
        inputRef: ElementRef,
        view: ViewContainerRef,
        factoryResolver: ComponentFactoryResolver
      ) {
        const compFactory = factoryResolver.resolveComponentFactory(
          SelectComponent
        );
    
        view.createComponent(
          compFactory,
          undefined,
          view.injector,
          [[inputRef.nativeElement]]
        );
    
      
      }
    
    

    Angular Version: 12.1.0

  12. jsdevtom commented on Nov 1, 2021

    @jsdevtom

    We ran into this issue with an async-triggered terms of service modal. The browser would throw an ExpressionChangedAfterItHasBeenCheckedError if the modal open call happened to trigger when the user has an [(ngModel)] form field in focus. We were able to workaround by doing this:

    this.service.mustRenewPolicyAgreement().subscribe((r) => {
      if (r) {
        try {
            document.activeElement.blur();
        } catch (e) {
            // do nothing
        }
        this.modal = this.modalService.open(this.modalTemplate, {
          centered: true,
          size: 'lg',
        });
      }
    }

    @markanye This works. Especially when dealing with large forms where you don't want to mark controls as touched before opening the modal. It is also very legitimate, as the error arises from the ng-touched class being set after the view has changed. Thus, ensuring that the ng-touched is already set to true (becuase it has been), by blurring the active element is a logical solution. Thank you.

  13. added
    feature
    and removed
    P2
    on Feb 8, 2022
  14. danielsuter commented on Nov 6, 2022

    @danielsuter

    Issue still exists on Angular 14.

  15. atscott commented on Dec 15, 2023

    @atscott
    Contributor

    This is fixed internally by 606de51 and will be available to enable via a private export in the next 17.1 release. We found it to be breaking in what appears to be very rare cases (see #53022 (comment)) so it won't land officially until v18.

  16. added a commit that references this issue on Mar 6, 2024
    a4090e8
  17. added a commit that references this issue on Mar 7, 2024
    ad045ef
  18. angular-automatic-lock-bot commented on Apr 6, 2024

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  19. locked and limited conversation to collaborators on Apr 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corecore: change detectionfeature

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions