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,
That sort of seems like overkill. Can’t you just do it with @Output
properties in the child?
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?
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?
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.
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>
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.