Search code examples
angularngoninit

Re-initializing a component or forcing it to run ngOnInit() again in Angular


I've got a table component in Angular that gets given different data depending on what the user has asked for and then populates a table. The table has gotten relatively complex and I need the entire component to essentially refresh when the user asks for something different. Is there a way to force the component to re-initialize when the user changes there selection on the parent component? Or maybe kill the component so that it has to re-load? I'm relatively new to Angular so I'm still trying to learn how the component life cycle works, any help would be greatly appreciated.


Solution

  • Create a utility function in your component, just make sure all the data required by your new state is ready.

    redirect(uri:string){
       this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
       this.router.navigate([uri]));
    }
    

    then use it like this

    this.redirect('//place your uri here');

    this function will redirect to a dummy route and quickly return to the destination route without the user realizing it.

    Approach 2: You can subscribe to router's navigation event.

     this.navigationSubscription = this.router.events.subscribe((e) => {
          // If it is a NavigationEnd event re-initialize the component
          if (e instanceof NavigationEnd) {
                // implement your refresh logic here 
              }
            }
          }
        });