redirect route angular code example

Example 1: redirect angular

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']);
}

Example 2: angular navigate using component

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

export class Component{ 				// Example component.. 
	constructor(private route:Router){} 
  
  	go(){
		this.route.navigate(['/page']); // navigate to other page
	}
}

Example 3: empty path redirection on home page in angular routing

/* Redirection of empty path on home page path in angular */

Now that we have added routing to the home and about components, let's see how to redirect users to the /home path when they first visit our app from the empty path.

We simply need to add a new route that matches the empty path and redirect it to the /home path as follows:

const routes: Routes = [
  { path: '', pathMatch: ‘full’, redirectTo: 'home' },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent }

];
Internally, the router uses a function called 'applyRedirects' to process redirects.

/*
I hope it will help you.
Namaste
Stay Home Stay Safe
*/

Example 4: how to add redirec router in angular

Angular Path Router Redirect