How to Refresh a Component in Angular How to Refresh a Component in Angular angular angular

How to Refresh a Component in Angular


After some research and modifying my code as below, the script worked for me. I just added the condition:

this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {    this.router.navigate(['Your actualComponent']);}); 


Use the this.ngOnInit(); to reload the same component instead reloading the entire page!!

DeleteEmployee(id:number)  {    this.employeeService.deleteEmployee(id)    .subscribe(       (data) =>{        console.log(data);        this.ngOnInit();      }),      err => {        console.log("Error");      }     }


Adding this to code to the required component's constructor worked for me.

this.router.routeReuseStrategy.shouldReuseRoute = function () {  return false;};this.mySubscription = this.router.events.subscribe((event) => {  if (event instanceof NavigationEnd) {    // Trick the Router into believing it's last link wasn't previously loaded    this.router.navigated = false;  }});

Make sure to unsubscribe from this mySubscription in ngOnDestroy().

ngOnDestroy() {  if (this.mySubscription) {    this.mySubscription.unsubscribe();  }}

Refer to this thread for more details - https://github.com/angular/angular/issues/13831