在使用单击的对象进行布线之后,要布线回前一组件

时间:2019-07-05 11:23:43

标签: angular angular6 angular-routing

我有三个组成部分headerlisthome

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

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

header组件放置在listhome组件中。

list组件中,我像这样在卡片中显示一些data

enter image description here

现在,当用户单击特定的卡时,用户将与单击的对象home一起路由到id组件,如下所示:

enter image description here

组件代码

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组件?

Stackblitz demo

1 个答案:

答案 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文件)

Forked_StackBlitz