首页 > 解决方案 > 在Angular中进行路由时如何将数据从组件传递到组件

问题描述

我知道@Input& @OutputinAngular 7 (2+)分别将数据从 Parent 传递给 Child 和 Child 传递给 Parent 。它在构建一个简单的应用程序时达到了目标。

但是现在我有了真实的应用程序和路由,出于某种原因,我需要将数据从父组件传递到子组件,反之亦然。

应用程序路由.config.ts

import { NgModule } from '@angular/core';
/* all imports */



const routes: Routes = [
{ path: '', pathMatch: 'full', component: AppComponent },
{ path: 'jobs', canActivateChild: [AuthGuard], component: HomeComponent, 
 children: [
 { path: 'list',       component: ListJobsComponent },
 { path: 'create', component: CreateJobComponent },
]},
{ path: 'not-found', component: NotFoundComponent },
{ path: '**', redirectTo: 'not-found' }
];


@NgModule({
 imports: [
  RouterModule.forRoot(routes)
 ],
 exports: [RouterModule]
 })
 export class AppRoutingModule { }

现在我需要将一些数据传递AppComponentListJobsComponent

app.component.html

<div class="container">
 <div class="page-header">
 <h1>Hello Angular7 </h1>
</div>
 <app-header></app-header>
 <router-outlet></router-outlet>
</div>

应用程序列表jobs.component.html

<div class="row">
 {{parentComponentData}}
</div>

应用程序列表jobs.component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-child',
templateUrl: './child.component.html',
 styleUrls: ['./child.component.css']
 })

 export class ChildComponent implements OnInit {
  @Input('parentComponentData') parentComponentData: string;
  @Output() onHit: EventEmitter<string> = new EventEmitter<string>();

  constructor() { }

  ngOnInit() {
  }}

我知道它可以以黑客方式实现,例如存储在 localStorage 或 sessionStorage 等。

如何以正确的方式传递这些数据?

谢谢!!

标签: angularcomponentsangular7angular-router

解决方案


推荐阅读