Robert
Robert

Reputation: 686

Passing data into a routed component with Angular2

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

Answers (2)

Matt Searles
Matt Searles

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

dddenis
dddenis

Reputation: 500

Providing a service with reactive data is the best solution.

Upvotes: 0

Related Questions