How to navigate to other page in angular 6?

前端 未结 4 441
粉色の甜心
粉色の甜心 2021-02-04 04:38

Im trying to redirect my page from login to another page. Im following this code.

My login component ts file:

import { Router } from \'@angular/router\';         


        
4条回答
  •  鱼传尺愫
    2021-02-04 05:16

    I am using angular 7 and I solved it in this way into my project.

    1.First We need to implement this Modules to our app.module.ts file

    import { AppRoutingModule} from './app-routing.module';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    
    @NgModule({
    
      imports: [
        BrowserModule,
        AppRoutingModule, 
        FormsModule,
      ],
    
    })
    

    2.Then Open your.component.html file and then fire a method for navigate where you want to go

    
    

    3.Then Go your.component.ts file for where you want to navigate. And add this code there.

    import { Router } from '@angular/router';
    
    export class YourComponentClassName implements OnInit {
    
        constructor(private router: Router) {}
    
        gotoHome(){
            this.router.navigate(['/home']);  // define your component where you want to go
        }
    
    }
    

    4.And lastly want to say be careful to look after your app-routing.module.ts where you must have that component path where you want to navigate otherwise it will give you error. For my case.

    const routes: Routes = [
      { path:'', component:LoginComponent},
      { path: 'home', component:HomeComponent },  // you must add your component here
      { path: '**', component:PageNotFoundComponent }
    ];
    

    Thanks I think, I share all of the case for this routing section. Happy Coding !!!

提交回复
热议问题