1

I have a parent-child component as below. Inside child.compontent.ts, I have a method : childFunction(). I want to call this method inside parent's function. How to achieve this ?

**Parent.html :** 

<div class="box">
    <input type="text" (input)="searchValue=$event.target.value" placeholder={{placeHolder}} />
    
<btn-icon [searchType]='searchType' [searchText]='searchValue'></btn-icon> // child component
</div>

**parent.component.ts :**

export class parentComponent implements OnInit {

parentFunction(){
// **Call** childFunction('inputValue');

}
 
**btn-icon  is Child :**
**btn-icon.component.ts:  (Child)**

export class btn-iconimplements OnInit {
  
  @Input() Type: string;
  @Input() Text: string;

childFunction(inputValue){
      //some logic
    }
}
 
user2294434
  • 123
  • 4
  • 16

3 Answers3

2

just use ViewChild to get the children

export class parentComponent implements OnInit {

@ViewChild(btn-icon) bt-icon //see that viewChild argument is 
                             //the classname of your child-component
  parentFunction(){
     this.bt-icon.childFunction('inputValue');
  }
}

You can also use a template reference and pass as argument to a function, e.g.

    <div class="box">
        <!--see how, in input event you pass the template reference "child" futhermore
                  $event.target.value-->
        <input type="text" (input)="change(child,$event.target.value)"
                 placeholder={{placeHolder}} />
        
      <!--see the "#child", it's a template reference-->
      <btn-icon #child [searchType]='searchType' [searchText]='searchValue'></btn-icon> 
    </div>
change(childComponent:bt-icon,value){
    chilComponent.childFunction(value)
}
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • Thank you ! This solution using @ViewChild works, provided I import the child component in the parent component . – user2294434 Jan 29 '21 at 03:52
0

You should use @ViewChild in the parent component:

export class parentComponent implements OnInit {
   @ViewChild(BtnIcon)    btnIcon;
   
   parentFunction(){
     btnIcon.childFunction();
   }

the btnIcon property will only be available and filled with the child component after the ngAfterViewInit() lifecycle hook.

Attention: I used the class name BtnIcon in camelcase and not as "btn-icon" as your example.

Eduardo Junior
  • 362
  • 1
  • 10
0

You can inject the Child Component using decorator @ViewChild():

@ViewChild(btn-icon)
private btnIcon: btn-icon;

Then you can access its properties like always:

this.btnIcon.childFunction();
DonJuwe
  • 4,477
  • 3
  • 34
  • 59