Passing child component initialization data back to Parent


#1

I am trying to make my parent component aware of how the child components are initializing themselves.

<Parent>
    <Child>In constructor, initialize a variable</Child>
</Parent>

So I tried emitting an event in the constructor, but the parent didn’t recognize it. I will go ahead and check whether or not I can emit to the parent in a different life cycle, but in the mean time - any advice would be great. THanks,


#2

Err, nvm - googled some resources that may work - bi-directional service.

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service


#3

That sort of seems like overkill. Can’t you just do it with @Output properties in the child?


#4

Is it good practice to stick an @Output var inside the constructor of the child component?

lets say my child has this -

@Input() myInputData: any;
@Output() sendToParent: EventEmitter = new EventEmitter();

constructor() {
   this.sendToParent.emit(myInputData);
}

I’ll go ahead and try it, but is it a better practice than the singleton method of using services? Even if its not an actual service but some variables both parent and child can use?


#5

Parent pseudo-template -

<ion-content> <!-- Parent Container -->
    <child (sendToParent)="catchAndRelease($event)"></child>
</ion-content>

Parent ts file -

catchAndRelease(e) {
   console.log(e); <!-- Nothing happens here -->
}

When the child emits the event in the constructor - it doesn’t catch in the catchAndRelease parent function. Any ideas where I went wrong?


#6

No, the constructor is too early for bound properties either way. Can you explain a bit more what you’re really trying to achieve? It seems unusual that these components would be so tightly coupled.


#7

I am trying to find a way to actually decouple them, lol.

I want a plugin architecture, “hot swapping” for parent/child components. I want to add and remove child components on the fly, and have the parent component be aware of this without having to hard code it.

<Parent>
    <Child 1><Click on something, it is removed
    <Child 2>
</Parent>

<Parent>
  <Child 3>Click a checkbox, it is added as needed
</Parent>

#8

This maybe what I’m looking for - http://stackoverflow.com/questions/40060498/angular-2-1-0-create-child-component-on-the-fly-dynamically#40080290


#9

I see. Good luck if you decide to head down that road. I tried it for a while, and eventually gave up on it in favor of this approach.