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>
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With