0

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?

bruh
  • 2,205
  • 7
  • 30
  • 42
  • 1
    If you don't pass it, you can't. You could share it through a service though, but that's another story – baao Jun 27 '18 at 21:35
  • How do you pass it when using router-outlet? – bruh Jun 27 '18 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 – bruh Jul 01 '18 at 02:29

1 Answers1

4

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

<child [secret]="secret"><child>
Sebastian Hildebrandt
  • 2,661
  • 1
  • 14
  • 20
  • My child is lazy-loaded and does only exists in router-outlet – bruh Jun 27 '18 at 21:37
  • 3
    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. – Sebastian Hildebrandt Jun 27 '18 at 21:48
  • 2
    @bruh Then why did not you mention in your question. – Vikas Jun 28 '18 at 04:18