ViewDestroyedError: Attempt to use a destroyed view: detectChanges

后端 未结 3 1437
离开以前
离开以前 2021-01-03 18:49

I have the following component that creates an MdDialog

export class SideNavsComponent implements OnInit, AfterViewInit, OnDestroy {
  eventDispatcher: Event         


        
相关标签:
3条回答
  • 2021-01-03 19:28

    Padegal Saigiriraj is right. But instead of ViewRef_ use ViewRef. In short:

    setTimeout(() => {
      if (this.cdr && !(this.cdr as ViewRef).destroyed) {
        this.cdr.detectChanges();
      }
    });
    

    ViewRef stands for Angular view, specifically the host view as Angular site describes.

    0 讨论(0)
  • 2021-01-03 19:31

    the reason that this issue is happening that you are deleting the reference on the sortableData or dragableData on the change event. in abstract class, the detectChange method is waiting for 250 ms before firing the change detect, at that time your view and component will be destroyed.

    setTimeout(() => {
            if (this.cdr !== null && this.cdr !== undefined &&
              !(this.cdr as ViewRef_).destroyed) {
              this.cdr.detectChanges();
            }
          }, 250);
    
    0 讨论(0)
  • 2021-01-03 19:40

    The issue is the close action of the dialog is removing the item from the view, and your EventDispatcher IS NOT AN ANGULAR METHOD so it fires outside the zone context and freaks it out. It goes like this:

    • Dialog exists in view, sets state
    • Clicks close
    • Fires your event to start
    • Your event is read (out of context)
    • Deletes from view (still out of context)
    • Change detection finally catches up to look for changes in your component, OH SNAP WHERE'S THE COMPONENT?

    You can either use a different method to communicate with the dialog, or switch to onPush() for change detection

    I suggest you Use the afterClosed handle instead:

    this. authEmailDialogRef.afterClosed().subscribe(result => {
      console.log(`Dialog result: ${result}`); // Pizza!
    });
    

    I pulled that snippet straight from the docs: HERE

    0 讨论(0)
提交回复
热议问题