Sunday 13 February 2022

How to navigate to other page in angular 6?

 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

<button class="btn btn-primary" (click)="gotoHome()">Home</button>

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 !!!

No comments:

Post a Comment