Reputation: 93
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
Upvotes: 1
Views: 2374
Reputation: 23838
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
Upvotes: 0
Reputation: 156
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.
Upvotes: 1