1

I need to route to my component and bind data in @Input.
I have a router link and i use it in different places to navigate to my component. And i need to pass different data when i route to my component from different places

I was trying this

this._router.navigate(['MyComponent', {title: 'something' }]);

I don't want to use this way because it will add some params to my URL link
I want it to be something like
< myComponent [data]='data'> And the catch it in @Input
@Input() data = data; // sorry if this code is wrong, it's just for example

Is there any way i can do this? or there's some other options to work around my situation? How can i route to component and bring some data with me

2
  • Does it need to be via @Input? If you don't want the data in the URL, you could put it in a service before navigating, and then pull it out of the service. Commented Jan 23, 2019 at 19:33
  • @FrankModica i don't think i can use service because i need to bind different data if i navigate from different places in my application, i don't know how it's possible from service Commented Jan 23, 2019 at 19:36

2 Answers 2

1

You can not add @Input param to route component. You can add static data :

{
   path: 'heroes',
   component: HeroListComponent,
   data: { title: 'Heroes List' 
 }

Note from docs:

The data property in the third route is a place to store arbitrary data associated with this specific route. The data property is accessible within each activated route. Use it to store items such as page titles, breadcrumb text, and other read-only, static data. You'll use the resolve guard to retrieve dynamic data later in the guide.

You can pass data in resolvers, (for example get data from server):

{
  path: 'heroes',
  component: HeroListComponent,
  resolve: { hero: HeroResolver }
}

Note from docs:

In summary, you want to delay rendering the routed component until all necessary data have been fetched.

For more info about resolvers: https://angular.io/guide/router#resolve-guard

Or you can get variable in component via service.

Sign up to request clarification or add additional context in comments.

Comments

0

Use ng-interconnect

All you have to do in your use case is to create a broadcaster outside the route and receive data from inside the route.

this.dataForRoute = interconenct.createBroadcaster(‘dataSender’);
...
this.dataForRoute.emit(data);

In the component behind the route -

interconnect.receiveFrom('dataSender', '', (data) => {
   //Here is your data
   console.log(data)
})

More detials: https://charlie-code.medium.com/simplify-your-angular-development-using-ng-interconnect-1b94c68e9141

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.