简体   繁体   中英

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

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, eg

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM