3

Imagine this Host Component code:

@Component({
    directives: [nestedComponentDirective]
})

export class ParentComponent {
     save():void {
            this.myService.myHTTPCall().subscribe((event) => {
                // if callback successfull we need to let directive know
            })
        }

Now the Nested Component:

@Component({
  selector: 'someSelector',
  template: `
  <div>
    <button [stuff]="stuff"</button>
  </div>`
})


export class ContinuationCheckDirective {
  @Input() waitingForHostedComp(value) {
    console.log ("value", value)
  }

How to call waitingForHostedComp from the Host-Component (Parent)?

2
  • Please provide more code. Where is save() and waitingForHostComp()? Commented Aug 1, 2016 at 13:21
  • save() is on ParentComponent importing the ChildComponent. waitingForHostComp() is on ChildComponent. Basically what I want is a listener on the ChildComponent that gets triggered when the ParentComponent (which injects the ChildComponent) gets an answer from the server. Commented Aug 1, 2016 at 13:29

1 Answer 1

7

The way you can do it is using ViewChild, i.e., we inject the child component into the parent as a ViewChild.

import { ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'parent-component',
  template: ` implements AfterViewInit
  <child-component></child-component>
  `,
  directives: [ChildComponent]
})
export class ParentComponent {
  @ViewChild(ChildComponent)
  private childComponent: ChildComponent;

  save(): void {
        this.myService.myHTTPCall().subscribe((event) => {
            this.childComponent.waitingForHostedComp(event);
        })
  }

}

You can see more details in the Component Interaction Cookbook: Parent Calls a ViewChild.

Sign up to request clarification or add additional context in comments.

4 Comments

Interesting.... will my other Inputs and Outputs work (I did not cite that in this code sample) as before?
Absolutely, they'll work as before. ViewChild is just a way to interact with you child component in the typescript code.
I had to put private childComponent: ChildComponent; into the constructor, and then it works perfectly. Thank you, Bernardo.
I'm glad to help @StephanKristyn!

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.