How to destroy a component when we move to another component in angular 6?

14,638

Solution 1

You can use nativeElement.remove() method to physically remove element. So your code could look as follows:

Make sure to put it in ngOndestroy method

export class YourComponent  {

  constructor(private elementRef: ElementRef) {

  }

  ngOndestroy() {
    this.elementRef.nativeElement.remove();
  }
}

Update:

Since you using router you need to change your router order like this

  {path: '', component:  HomepageComponent }
  {path: 'ide',component: OnlineideComponent},

Solution 2

You can use HostListener and it will remove/clear the component when that page is unloaded.

@HostListener('unloaded')
ngOnDestroy() {
    console.log('Cleared');
}
Share:
14,638
mahbubcseju
Author by

mahbubcseju

I have a great enthusiasm on programming and learning various algorithms. I have solved more than 2000 programming problems in different online judges. I have participated in more than 200 different programming contests (online/onsite). I always love problem solving as well as creation of programming challenges.

Updated on June 08, 2022

Comments

  • mahbubcseju
    mahbubcseju almost 2 years

    In angular 6, let we have three component x,y,z . I am in now at x component. But when I go to component y and return back to x, there is still the previous x component in the DOM. But I want to delete the previous instance of x.That means I want only one intstance of a component at a time in DOM.How to do that ?

    My Router config part :

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { OnlineideComponent} from './onlineide/onlineide.component';
    import {HomepageComponent} from './homepage/homepage.component';
    
    const routes: Routes = [
      {path: 'ide',component: OnlineideComponent},
      {path: '', component:  HomepageComponent }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    
  • Tony Ngo
    Tony Ngo almost 5 years
    @mahbubcseju how did you create a component ? are you dynamic create a component or just navigate between component using router
  • mahbubcseju
    mahbubcseju almost 5 years
    navigate between component using router.
  • Tony Ngo
    Tony Ngo almost 5 years
    Then the component should be delete by itself. Can you show me the router config
  • mahbubcseju
    mahbubcseju almost 5 years
    { path: 'my/path/', component: MyComponent } like that ? Actually I didn't get which is the router config .
  • Tony Ngo
    Tony Ngo almost 5 years
    Please upload the router config code in your question. I think the main problem come from your router config
  • mahbubcseju
    mahbubcseju almost 5 years
    I have added router config code .please have a look .