我有三个组成部分header
,list
和home
在header
组件的list
组件中,路由路径将如下所示:
<div>
<a [routerLink]="['../list']" >List</a>
</div>
此header
组件放置在list
和home
组件中。
在list
组件中,我像这样在卡片中显示一些data
:
现在,当用户单击特定的卡时,用户将与单击的对象home
一起路由到id
组件,如下所示:
组件代码
home.html
<app-header></app-header>
<h2>List Component</h2>
<div *ngFor="let contact of contacts" >
<mat-card [routerLink]="['../home' , contact.id]" >
<h4>{{contact.contactName}}</h4>
<p>{{contact.email}}</p>
</mat-card>
</div>
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ListComponent } from './list/list.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '', component: ListComponent },
{ path: 'list', component: ListComponent },
{ path: 'home/:id', component: HomeComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule { }
home.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
public id: string;
public sub: any = {};
constructor(public route: ActivatedRoute) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = params['id'];
});
console.log(this.id);
}
}
home.html
<app-header></app-header>
<h2>Home Component</h2>
Clicked ID ==> {{id}}
现在的问题是:
home
组件时,网址将为https://XXXX-XXX-XX/home/02
home
组件开始,如果我单击list
(出现在标题组件中),则网址正在更改https://XXXX-XXX-XX/home/list
如何从
list
组件路由回到home
组件?
答案 0 :(得分:1)
通过添加:
{ path: 'list', component: ListComponent }
因此您的路线将如下所示:
const routes: Routes = [
{ path: '', component: ListComponent }, -- for default page
{ path: 'list', component: ListComponent },
{ path: 'home/:id', component: HomeComponent },
];
和HTML代码:
<div>
<a [routerLink]="['/list']">List</a>
</div>
当前代码的问题:
您正在使用../list
,其中..
表示一个路径级别的升级(因此,如果您位于/home/home.component.html
上,并且输入了../list.component.html
,则它指向的文件夹是home
,然后搜索list.component.html
文件)