【问题标题】:How to call child components method from parent component如何从父组件调用子组件方法
【发布时间】:2021-05-02 05:20:42
【问题描述】:

我有一个父子组件,如下所示。 在 child.component.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
    }
}
 

【问题讨论】:

标签: angular typescript components parent-child


【解决方案1】:

只需使用 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 的此解决方案有效。
【解决方案2】:

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

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

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

this.btnIcon.childFunction();

【讨论】:

    【解决方案3】:

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

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

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

    注意:我在驼峰式中使用了类名 BtnIcon,而不是像您的示例中的“btn-icon”。

    【讨论】:

      猜你喜欢
      • 2018-06-08
      • 2020-06-27
      • 2016-12-08
      • 2020-06-15
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      相关资源
      最近更新 更多