在单击 object 路由后路由回上一个组件

To route back previous component after routing with clicked object

我有三个组成部分 header , list & home

header 中,list 组件的路由路径将如下所示:

  <div>
    <a [routerLink]="['../list']" >List</a>
  </div>

header 组件被放置在 listhome 组件内。

list 组件中,我在卡片中显示了一些 data,如下所示:

现在,当用户点击特定卡片时,用户将连同点击的 object id 一起路由到 home 组件,如下所示:

组件代码

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}}

现在的问题是:

How can i route back to list component from home component?

Stackblitz demo

通过添加:

{ 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 文件)

Forked_StackBlitz