Search code examples
angulartypescriptcomponentsparent-child

How to call child components method from parent component


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
    }
}
 

Solution

  • 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();