Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect Page in Angular?

Tags:

html

angular

I'm Trying to redirect one component to another (like page redirect)

Angular link

here is my code

app-routing.module.ts

import { RoleComponent } from './role/role.component';
import { AppComponent } from './app.component';
import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: '/AppComponent', pathMatch: 'full' },
  { path: 'role', component: RoleComponent },

];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

top-header.component.html

 <ul class="navbar-nav mr-auto">
       <li class="nav-item">
          <a class="nav-link" href="#">Verified</a>
        </li>
        <li class="nav-item">
          <a routerLink="/role" class="nav-link" href="#">ROLES</a>
        </li>
      </ul>

AppComponent.html

<div class="container p-md-0">
<app-top-header></app-top-header>
<router-outlet></router-outlet>
<app-main-contain></app-main-contain>
</div>
like image 967
Dhrupal Suthar Avatar asked May 15 '18 05:05

Dhrupal Suthar


People also ask

What is redirect in Angular routing?

When the application start, it navigates to the empty route by default. We can configure the router to redirect to a named route by default. So, a redirect route translates the initial relative URL (”) to the desired default path.


1 Answers

You can use router.navigate function of the Router class. Just import Router from @angular/router and create a object for it in the constructor(private router: Router) and use router.navigate(['/roles']);

import { RoleComponent } from './role/role.component';
import { AppComponent } from './app.component';
import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: '/AppComponent', pathMatch: 'full' },
  { path: 'role', component: RoleComponent },

];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {
  constructor(private router: Router)
}

functionOnWhichRedirectShouldHappen(){
  router.navigate(['/role']);
}

HTML

<ul class="navbar-nav mr-auto">
   <li class="nav-item">
       <a class="nav-link" href="#">Verified</a>
   </li>
   <li class="nav-item">
      <button (click)="functionOnWhichRedirectShouldHappen()">ROLES</button>
   </li>
</ul>
like image 177
Deepshikha Chaudhary Avatar answered Oct 25 '22 07:10

Deepshikha Chaudhary