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