Reputation: 686
I have a component that's loaded via routing and I'm trying to pass data into the component from a parent component. How would I go about doing this?
Parent Component Class
export class HomeComponent{
userName: string;
userId: string;
ngOnInit(): void{
this.userName = "user name";
this.userId = "user id";
}
}
Parent Component Template
<div>
<p>Parent Component</p>
</div>
<router-outlet></router-outlet>
Child Component Class
export class ChildComponent{
userName: string;
userId: string;
}
Basically, the home component has child routes that are only available to that component. The child component is automatically loaded along with the parent component, but I want to use the data from the parent component, inside the child component. For practicality purposes and not having questions about whether my application is set up correctly, it is.
Upvotes: 0
Views: 93
Reputation: 2765
You can pass variables via the Router if you want to, eg.
const routes =
[
{ path: "child/:customerId", component: ChildComponent },
]
Then you can access customerId
via the ActivatedRouteSnapshot
eg.
class ChildComponent
{
constructor(route : ActivatedRouteSnapshot)
{
const customerId = +route.params["customerId"];
}
}
Upvotes: 1