简体   繁体   中英

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 }
];

@NgModule({
  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() {
    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},

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

@HostListener('unloaded')
ngOnDestroy() {
    console.log('Cleared');
}

This is what I did to make it work.

Use routerLink and <router-outlet></router-outlet> . You can do something like this.


<button mat-flat-button color="primary" routerLink="/login">Login</button>
<button mat-flat-button color="primary" routerLink="/signup">Signup</button>

<router-outlet></router-outlet>

Your Components will show in place of <router-outlet></router-outlet> and they will destroy previous component. [ Source ]

Thoughts: I believe this way of routing is done because of the 'nature' of the Single Page Applications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM