Within one of my Angular 2 routes templates, specifically in FirstComponent, there is a button present.
first.component.html
<div class="button" click="routeWithData()">Pass data and navigate</div>
The main objective here is to:
When the button is clicked -> navigate to another component while carrying over the data without utilizing the other component as a directive.
This is what I have attempted so far...
1ST METHOD
In the same view, I am collecting the same data based on user interaction.
first.component.ts
export class FirstComponent {
constructor(private _router: Router) { }
property1: number;
property2: string;
property3: TypeXY; // this is an actual class, not a primitive type
// Various class methods set the properties mentioned above
// DOM events
routeWithData(){
// Navigate here
}
}
Typically, I would navigate to SecondComponent by
this._router.navigate(['SecondComponent']);
And pass the data like so
this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);
wherein the link definition with parameters would be
@RouteConfig([
// ...
{ path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent}
)]
The downside of this method is that I believe I cannot pass complex data (like an object such as property3) through the URL;
2ND METHOD
An alternative approach would involve including SecondComponent as a directive within FirstComponent.
<SecondComponent [p3]="property3"></SecondComponent>
However, my intention is to actually navigate to that component instead of just including it!
3RD METHOD
The most practical solution that comes to mind is to utilize a Service (for example, FirstComponentService) to
- store the data (_firstComponentService.storeData()) when routeWithData() is called in FirstComponent
- retrieve the data (_firstComponentService.retrieveData()) in ngOnInit() within SecondComponent
Even though this method appears to be effective, I question whether it is the simplest / most elegant way to achieve the desired outcome.
Overall, I would like to explore any potential alternative approaches for passing data between components, especially with the least amount of code possible.