Skip to content

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

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 }

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export class AppRoutingModule { }



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() {


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

  {path: '', component:  HomepageComponent }
  {path: 'ide',component: OnlineideComponent},
User contributions licensed under: CC BY-SA
10 People found this is helpful