Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a parent component function from a child component in Angular [closed]

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?

like image 209
LLaza Avatar asked Jun 10 '17 03:06

LLaza


1 Answers

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($event)"></child-component>

and then in your component

test(msg){
    console.log(msg);
}
like image 195
Hamed Baatour Avatar answered Nov 04 '22 10:11

Hamed Baatour