Duplicate Question: Yes. Here it is.
As above question is already asked before but not found any useful answers due to question not properly demonstrates the problem.
Scenario / Problem: I'm using Angular4 and my project is based on Lazy Loading. I've a login page in which I've a button called "Register" when I clicked on my register button it navigate to register module and run its component. The problem which I was facing is when I click on register button my register module loaded properly but my login module not remove from DOM and exists on same page.
Below is the screen shot before I clicked on register button:
Below is the screen shot after I clicked on register button:
Below is my folder structure:
Below is my app-routing.module.ts:
const routes: Routes = [
{
path: '',
pathMatch: 'full',
component: AppComponent
},
{
path: 'login', pathMatch: 'full',
data: { gotoLogin: true },
canActivate: [ AuthService ],
loadChildren: './modules/login/login.module#LoginModule'
},
{
path: 'register', pathMatch: 'full',
data: { gotoRegister: true },
canActivate: [ AuthService ],
loadChildren: './modules/register/register.module#RegisterModule'
}
{
path: 'dashboard',
data: { requiresLogin: true },
canActivate: [ AuthService ],
loadChildren: './modules/dashboard/dashboard.module#DashboardModule'
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Below is my login.component.ts:
constructor(
private _fb: FormBuilder,
private _Router: Router,
private _User: UserService,
public toastr: ToastsManager, vcr: ViewContainerRef) {
this.toastr.setRootViewContainerRef(vcr);
this.UserForm = _fb.group({
"_Username" : ['', Validators.required],
"_Password" : ['', Validators.required]
});
if (this._User.IsUserLoggedIn()) {
this._Router.navigate(['/dashboard']);
}
else {
this._Router.navigate(['/login']);
}
}
ngOnInit() {
if (this._User.IsUserLoggedIn()) {
console.log('User successfully loggedin.')
this._Router.navigate(['/dashboard']);
}
}
navigate() {
this._Router.navigate(['/register']);
}
Below is my login.component.html:
<button class="btn btn-warning" type="button" (click) = "navigate()">Register</button>
Below is my login.router.ts
const routes: Routes = [
{
path: '', pathMatch: 'full',
component: LoginComponent
}
];
@NgModule({
imports: [
RouterModule.forChild(routes),
FormsModule,
ReactiveFormsModule
],
declarations: [LoginComponent],
exports: [RouterModule]
})
export class LoginRouter { }
Below is my app.component.html
<router-outlet></router-outlet>
Below is my app.component.ts
export class AppComponent {
title = 'app works!';
constructor(
private _Router: Router) {
this._Router.navigate(['/login']);
}
ngOnInit() {
}
}
I hope I provide brief information regarding my problem. Now what I want is when I click on register button and its navigate to register module then only register module will open and remove all previous modules from DOM.