angularroutesviewchild

Angular go back to page, viewChild is undefined


I have such a sceneario; component A goes to B and when I go back to A , the @viewChild element is undefined. I tried to access it in ngAfterViewInit, ngAfterContentInit but it's always undefined. This is the last I tried:

@ContentChild('item', { static: false }) item: ItemComponent;

 ngAfterContentInit() {
 if (this.item) {
          this.item.resetFilters();
}

EDIT

I also use data that was in the component so I need to know that now I come from back and it's not new navigation :

 if (event.restoredState))
      this.setSavedData()

Solution

  • Back button, causes SPA applications to not work well, because the state is lost at the previous screen, you can trigger a reload of the component using the below code.

    You can place this code at the root of your application like app.component.ts.

    Below code does not refresh screen but reloads the component.

    import { HostListener } from '@angular/core';
    
    constructor(private router: Router) {}
    
    @HostListener('window:popstate', ['$event'])
    onBackButton(event) {
      this.router.navigateByUrl(`${window.location.pathname}`, {
        skipLocationChange: true,
        onSameUrlNavigation: 'reload',
      });
    }
    

    You can also refresh the page on back button press.

    import { HostListener } from '@angular/core';
    
    @HostListener('window:popstate', ['$event'])
    onBackButton(event) {
      location.reload()
    }
    

    EDIT

    I also use data that was in the component so I need to know that now I come from back and it's not new navigation :

     if (event.restoredState))
          this.setSavedData()