Jay Bumjun Kim
Jay Bumjun Kim

Reputation: 113

Angular - How to send Data from Child Component to Parent with Routing?

I want to set a SampleData and send it to Parent Component in Angular. It works fine when the Child Component purely inside of Parent Component.

However, I want to set different Child Components in a Parent Component by Routing.

so I put in parent.component.html, and the Child Component is called like this and does not work anymore...

{ path: "sample1", component: Sample1Component }

Can anyone see my code and give me a solution...?

Center Component would be a Parent Component, and Sample1 Component would be a Child Component.

You may download the code to see more detail from Here

app.router.module.ts

const AppRoutes: Routes = [
  { path: "", redirectTo: "/", pathMatch: "full" }, 
  { path: "sample1", component: Sample1Component },
  { path: "**", redirectTo: "/", pathMatch: "full" } 
];

center.component.html

<div (sampleEvent)="SampleData = $event">
  Center Area Title from Sample 1 : {{ SampleData }}
</div>

<!--if sample 1 Component is called by this Router, 'Center Area Title value does not change -->
<router-outlet></router-outlet>

<!-- if sample 1 Component is called by below, 'Center Area Title value changes-->
<!-- <app-sample1 (sampleEvent)="SampleData = $event"></app-sample1> -->

sample1.component.html

<input type="text" placeholder="Center Area Title" #sampleTitle (keyup)="onChange(sampleTitle.value)"  />

sample1.component.ts

export class Sample1Component implements OnInit {
  @Output("sampleEvent") sampleEvent = new EventEmitter();

  onChange(value) {
    console.log(value);
    this.sampleEvent.emit(value);
  }

  constructor() {}
  ngOnInit() {}
}

Please somebody help me out here....

Upvotes: 1

Views: 1114

Answers (1)

Mike Hill
Mike Hill

Reputation: 3772

Route components do not have an inherent relationship to the component which contains the RouterOutlet (<router-outlet>). It is likely possible to find a way to emit data from the routed component through the RouterOutlet, but this is not the canonical way of solving this problem. A more conventional solution would be to use an external singleton (service) which houses observables used to transfer data between components which do not have a direct inheritance relationship.

  1. Create an @Injectable() service class with an Subject field for the event
  2. Add this service to the module providers
  3. Inject this service into both the route component (Sample1Component) and the container component (CenterComponent)
  4. Listen to changes to the observable field in the container component (CenterComponent)
  5. Emit changes to the observable subject in the route component (Sample1Component)

Upvotes: 3

Related Questions