如何从父组件调用子组件方法

How to call child components method from parent component

我有一个父子组件如下。 里面 child.compontent.ts, 我有一个方法:childFunction()。 我想在父函数中调用这个方法。 如何实现?

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

只需使用 ViewChild 获取子项

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

您还可以使用模板引用并将其作为参数传递给函数,例如

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

你应该在父组件中使用@ViewChild

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

btnIcon 属性 仅在 ngAfterViewInit() 生命周期挂钩后可用并填充子组件。

注意:我使用 class 驼峰命名 BtnIcon,而不是您示例中的“btn-icon”。

您可以使用装饰器注入子组件@ViewChild():

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

然后您可以像往常一样访问它的属性:

this.btnIcon.childFunction();