Search code examples
templatesangularcomponentsparent-childemit

Angular 2: emit from child component directly to the parent component's script file


I have a nested component that I wish to emit some data directly to the parents typescript file without going through the template. I can't use <child (childEvent)="parentFunc()"></child>

Is this possible? If so, how?

This is the current state of things.

parent.component.html (The element must be this)

<child #child> </child>

parent.component.ts

@ViewChild('child') public child;

public doSomething() {
  this.child.work();
}

public doThisWhenChildEmits(someData) {
  //?????How do I call this function from child without going through the DOM
  alert(It worked)
}

child.component.ts

@Output() private childEvent: EventEmitter<any> = new EventEmitter()
...
public work() {
   // does some work that changes the child's template
}

public clickToSendBack(){
   // click event that sends back to parent.component directly????
   this.childEvent.emit(someData);
}

Solution

  • If you do not want to use @Output you could use Subject instead:

    Your parent would subscribe to changes. In your parent, declare a Subject in component and in the constructor subscribe to changes:

    public static changesMade: Subject<any> = new Subject();
    
    //inside constructor the following
    ParentComponent.changesMade.subscribe(res => {
      //call your method here, with the res (someData) you receive from child
      this.doThisWhenChildEmits(res);
    });
    

    and in your child:

    public clickToSendBack(){
       // send the data to parent
       ParentComponent.changesMade.next(someData)
    }
    

    Let me know if this helps! :)