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
decorator,可以访问子属性和方法。然后在您的按钮中添加一个点击处理程序,并在您的子按钮中调用refresh
方法
您可以找到的详细描述
您可以将商店添加到应用程序中,并侦听商店中的事件。这是一种更好的方法,但对于中大型应用程序来说,这是一种很好的方法。是否也可以同时刷新多个组件?我尝试了三个组件,第一个是更新的,另外两个是输出错误。你知道这个问题吗?你可以试试看孩子们。您可以使用它获取子组件列表。
@ViewChild(ChildComponent) child:ChildComponent;
onRefreshClick(){
this.child.refresh()
}