marcel
marcel

Reputation: 3272

Angular2 Router-Outlet Component Event-Emitting (A2 >= v1.2.0)

I'd like to receive events from my routed components and pass data into them, from the parent component.

Content-App-Template:

<router-outlet [data]='data' (selected)="selected($event)"></router-outlet>  //this is not working

A 'content-app' component should receive events from a routed component (e.g. 'content-app-list')

<content-app>  // this is where the events should arrive
   <content-app-header></content-app-header>
   <router-outlet></router-outlet>    
   <content-app-list></content-app-list>    //this is a routed component, that emits events and should bind data
</content-app>

I could implement a service that handles the data, but I prefer a framework-concept.

Upvotes: 1

Views: 763

Answers (1)

LordTribual
LordTribual

Reputation: 4249

As of now, you cannot directly pass data to routed components. There's also been an issue on GitHub from 2015. However, the issue is closed and the feature is currently not supported. There are basically three options:

  1. Shared service
  2. Pass data via url or query params
  3. Inject parent component into child's constructor

The first option is definitely the cleanest way to achieve this. There is also a very good article on component interaction. However, make sure to manage your subcriptions well, if you use Observables or Subjects for yor shared service. Since the service will be a singleton it will actually stay alive and in memory.

The second option is also a valid approach I would say. By injecting ActivatedRoute you could even subscribe to the params, since the router leverages Observables as well. You could implement this as follows:

constructor(private activatedRoute: ActivatedRoute) { }

ngOnInit() {
  this.paramSubscription = this.activatedRoute.params.subscribe(...);
}

ngOnDestroy() {
  this.paramSubscription .unsubscribe();
}

As you can see, all you have to do is inject ActivatedRoute and then subscribe to the params in the ngOnInit lifecycle hook. As mentioned, make sure to unsubscribe in ngOnDestroy.

The third option is to inject the parent component via DI into your child component.

constructor(private _parentComponent: ParentComponent)

You can then call methods and get data from your parent component. Notice, the first parent of that type is being injected.

Bottom line is that I would suggest you to use a shared service or url / query params if possible.

Upvotes: 2

Related Questions