0

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.

1
  • Provide a service at the parent component, inject it in the child component. Ideally use one or more Observables (BehaviorSubject) in the service to pass the values along. Commented Nov 1, 2017 at 19:51

2 Answers 2

1

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"];
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Providing a service with reactive data is the best solution.

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.