我在使用angular的路由导航方法时遇到了问题 . 我有两个组件:LoginComponent和HomeComponent . 当我点击“login.component.html”中的按钮时,我想重定向到“home.component.html” .
- app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{path: 'home', component: HomeComponent}
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent
],
imports: [
BrowserModule, RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- login.component.html
<button class="btn btn-primary" (click)="goHome();" class="clickable">Home</button>
- home.component.html
<p>
home works!
</p>
URL会更改但它仍保留在同一个组件页面中 .
- login.component.ts
从'@ angular / core'导入{Component,OnInit};
从'@ angular / router'导入;
@零件({
选择器:'app-login',
templateUrl:' . / login.component.html',
styleUrls:[' . / login.component.css']
})
导出类LoginComponent实现OnInit {
构造函数(私有路由器:路由器){}
ngOnInit(){
}
回家() {
this.router.navigate([ '家']);
}
}
2 回答
添加以下内容:
<button class="btn btn-primary" (click)="goHome();" class="clickable">Home</button>
或通过
<a>
.如果您打算将其附加到当前路径,请删除
/
.如果要在模板中加载多个路径,则可以在app.component模板中使用:
如果要加载嵌套路由,请尝试使用:
并在a标签中使用routerLink指令,然后传递路径中指定的路由
希望它有用 .