Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何使用click事件从父组件中的子组件刷新表内容?_Angular_Typescript_Event Binding - Fatal编程技术网

Angular 如何使用click事件从父组件中的子组件刷新表内容?

Angular 如何使用click事件从父组件中的子组件刷新表内容?,angular,typescript,event-binding,Angular,Typescript,Event Binding,我在子组件中创建了一个表,并在其中存储了一个刷新函数。现在我想在我的父组件中调用它,并通过单击按钮来执行它。你能告诉我怎样才能实现这一点吗 我的代码: // Child-Component ngOnInit() { this.refresh(); } /** * Refresh Data Table */ public refresh() { if (!this.isLoading) { this.all = false; this.cle

我在子组件中创建了一个表,并在其中存储了一个刷新函数。现在我想在我的父组件中调用它,并通过单击按钮来执行它。你能告诉我怎样才能实现这一点吗

我的代码:

// Child-Component

ngOnInit() {
this.refresh();
}

  /**
   * Refresh Data Table
   */
  public refresh() {
    if (!this.isLoading) {
      this.all = false;
      this.clearRows();
      this.loadData();
    }
  }

  public clearRows() {
    const formArray = this.salesAreaForm.get('rows') as FormArray;
    formArray.clear();
  }

//父组件
刷新子组件

您可能会将子组件作为viewchild获取,并直接在组件上调用该方法

import { ..., ViewChild } from '@angular/core';

@ViewChild(ChildComponent) childComponent: ChildComponent;

...
childComponent.refresh();
...
@ViewChild(ChildComponent)ChildComponent:ChildComponent;
onClick(){
childComponent.Refresh()
}
我通常更愿意为此使用服务,尽管您应该在父组件中使用

import { ..., ViewChild } from '@angular/core';

@ViewChild(ChildComponent) childComponent: ChildComponent;

...
childComponent.refresh();
...

有多种方法可以做到这一点

  • 共享服务 您可以为父组件和子组件之间的通信添加共享服务。它还将允许双向通信。你可以找到详细的信息

  • @ViewChild 在父类中添加以下内容:

  • 通过使用
    ViewChild
    decorator,可以访问子属性和方法。然后在您的按钮中添加一个点击处理程序,并在您的子按钮中调用
    refresh
    方法

    您可以找到的详细描述

  • 状态管理

  • 您可以将商店添加到应用程序中,并侦听商店中的事件。这是一种更好的方法,但对于中大型应用程序来说,这是一种很好的方法。

    是否也可以同时刷新多个组件?我尝试了三个组件,第一个是更新的,另外两个是输出错误。你知道这个问题吗?你可以试试看孩子们。您可以使用它获取子组件列表。
    @ViewChild(ChildComponent) child:ChildComponent; 
    onRefreshClick(){ 
        this.child.refresh() 
    }