0

I knew about @Input & @Output in Angular 7 (2+)to pass data from Parent to Child and Child to Parent respectively. It hit the target when building a simple app.

But now I have real-world app & routes in place & for some reason, I am in need to pass data from parent component to child component and vice-versa.

app-routes.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 { }

Now I need to pass some data from AppComponent to ListJobsComponent

app.component.html

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

app-list-jobs.component.html

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

app-list-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() {
  }}

I know it could be implemented in hack way like storing in localStorage or sessionStorage & so on.

How can I pass this data in the right way ?

Thanks!!

Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • 1
    you can create a service, which will have a variable which will be set in app.component and loaded in app-list-jobs.component – porgo Apr 18 '19 at 09:48
  • If "some data" is reasonably small, then you can put it in query params. – mbojko Apr 18 '19 at 09:49

0 Answers0