3

How do I get a variable from the parent, from a child component?

app.component

secret: string = '123'

child.component

@Input() secret;

console.log(this.secret);
=> undefined

Every example only shows template binding, for example [secret]="secret"

How do I just access the parent component's data from the child component?

3
  • 1
    If you don't pass it, you can't. You could share it through a service though, but that's another story Commented Jun 27, 2018 at 21:35
  • How do you pass it when using router-outlet? Commented Jun 27, 2018 at 21:42
  • 3
    @Vikas you downvoted because you can't read. Sebastian Hildebrandt recommended using a service to pass data. Thats why I upvoted his comment, because he made a valid suggestion and not a useless link like you did. I clearly stated that I'm looking for a way to pass data without using templates. Whats not clear about that? If you don't know the answer, don't answer. I see you get your upvotes by posting useless links and hope to get celebrated by other passive aggressive people instead of actually answering things Commented Jul 1, 2018 at 2:29

1 Answer 1

5

Try it with property binding in the HTML of your parent (where you are using the child component) like so:

<child [secret]="secret"><child>
Sign up to request clarification or add additional context in comments.

3 Comments

My child is lazy-loaded and does only exists in router-outlet
Another possibility would be then to create a service where you "store" the value from the parent and then read from that service in the child ... if the child component should react on changes of the parents value, you need to implement the service as an observable where you then can subscribe in the child component.
@bruh Then why did not you mention in your question.

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.