Reputation: 2290
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 { }
Upvotes: 10
Views: 36515
Reputation: 20092
You can use nativeElement.remove() method to physically remove element. So your code should be:
First, 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},
Upvotes: 7
Reputation: 752
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.
Upvotes: 0
Reputation: 61
You can use HostListener and it will remove/clear the component when that page is unloaded.
@HostListener('unloaded')
ngOnDestroy() {
console.log('Cleared');
}
Upvotes: 5