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 { }
As long as You ain't using some hack like display: none to hide the component from the DOM by including both the component in same parent component and hiding one or other component conditionally. i.e X component will be destroyed and will be recreated if the route is changed from X to Y and from Y to X.
because you want to unload the component, not merely hide it. export class ImageModalComponent implements OnInit { @Output() close = new EventEmitter(); public hideModal() { this. close. emit(); // here we tell the parent that the "close" button has been clicked. } }
To force a component to be destroyed, you use the HostListener from the Angular Core library. When using HostListener , you specify the event you want to listen to on the host of the component. In our case, we listen for the unloaded event so that when the page is unloaded, ngOnDestroy() will be triggered.
@Padrezz you just need to remove the component out of the rendered html and it will be automatically destroyed. To do this you would just use a blade @if conditional, to conditionally render the child component.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With