I have home component in homeModule and contactUs componenent in contactModule.
When I click cancel in contactUs component, it should redirect us to Home.
routes
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule, Routes} from '@angular/router';
import {homeComponent} from './home/home.component';
const routes: Routes = [
{ path: 'home', component: homeComponent},
{ path: 'demo-ui/home', component: homeComponent},
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule],
declarations: []
})
export class AppHomeRoutingModule {
}
I tried the following code but it didnt work
import { Component, OnInit } from '@angular/core';
import { FormsModule, Validators, NgForm } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
//some code
})
export class contactUsComponent implements OnInit {
constructor( private router: Router ){
}
ngOnInit() {
}
redirect(){
this.router.navigateByUrl('/home'); }
}
//html
<button class="btn btn-primary" type="button" (click)="redirect()">
Cancel </button>
Also, I tried
<button class="btn btn-primary" type="button" [routerLink]="['/home']"> Cancel </button>
and
<button class="btn btn-primary" type="button" routerLink="/home"> Cancel </button>
Error: Cannot match any routes. URL Segment './home'
您需要使用锚标记才能使routerLink
正常工作。
<a class="btn btn-primary" role="button" routerLink="/home">Cancel</a>
Create function in your .ts
Like this :
redirectToHome(){
this.router.navigate(['/home']);
}
and call into your html
<button (click)="redirectToHome()">Cancel</button>
您可以使用:this.router.navigate(['home']);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.