LLaza LLaza -4 years ago 177
TypeScript Question

Call a parent component function from a child component in Angular

I am trying to call my

close()
function which is in the parent component from the child component in Angular.

Here is my code on Plunker, I tried to import the component and call the function directly in my child component but I get this error: Cannot read property 'close' of undefined

How can I fix this?

Answer Source

Assalamu Alaikum,

I will try to give a complete answer to both cases that you may encounter:

Case 1: Calling a child function from the parent component

You can achieve this simply by using a template variable on your child selector to reference your child component in your parent component template and then you can call any public functions or property using that reference.

so in your child component, you got a function:

test(){
console.log(`this is a test`);
}

and in your parent component you can call it in your parent component let's say after a button click just like this:

<child-component #childRef></child-component>
<button (click)="childRef.test()">Call the child test function</button>

Case 2: Calling a parent function from the child component

This is a case it's up to your use case as you can inject the parent component in the child component and do the same as above but the relation is no longer be parent-child or child-parent but both components will be strongly linked together which is a rare use case. Alternatively, you can get the same result in a very simple way by using the @Output decorator to pass data and create your function in your child that will consume the data passed in.

so in your child component, you do the following:

@Output() childEvent = new EventEmitter();
test(){
this.childEvent.emit('this is a test');
}

in your parent template

<child-component (childEvent)="test(message)"></child-component>

and then in your component

test(msg){
console.log(msg);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download