![](/img/trans.png)
[英]How to get data from parent form component to child component nested components data from parents to children
[英]Angular get status of all children components from parent component
我有“父级”和“子级”组件。我们可以从“父级”中添加或删除子级。 所以孩子们充满活力。 在父级中,我已经像下面这样循环渲染了子级组件
Parent.component.html
<child *ngFor="let child of children" [data]="child"></child>
现在在子组件中,我添加了一个名为IsValid()的函数来检查子组件是否有效
Child.component.ts
IsValid()
{
//check validity of component and return true if valid else false
}
在父组件中,我有一个名为“保存”的按钮,如果所有子项都有效,则必须启用该按钮,否则需要禁用该按钮。
因此,我需要一种方法来从父级中为每个子组件调用子组件IsValid函数,然后确定有效性结果并将其应用于“保存”按钮以启用或禁用
我尝试过的
1.我从孩子向父母发出了有效或无效的结果,如果任何孩子的结果无效,则我禁用了保存按钮。
但是这里的问题是:如果我添加了一个孩子,使其生效,将启用保存按钮。 现在,我添加了另一个无效的子项,因此将禁用保存按钮,但是如果我删除无效的子项,则将禁用子项保存按钮,尽管我们只有一个有效子项。因为IsValid事件仅在当前子项发生更改时被发出。
2.我可以用这样的东西
<child #varName></child>
@ViewChild('varName') childElement;
然后从父母那里我可以打电话
childElement.IsValid()
但是由于我已经在循环中渲染了childs,因此如何在循环中给出唯一的名称以及如何在ts文件中添加对该唯一HTML标记的引用。
我在这里创建了案例SlackBlitz
任何帮助将不胜感激。 谢谢
您可能要使用@ViewChildren
在您的父组件中:
@ViewChildren(ChildComponent) children: QueryList<ChildComponent>;
areChildrenValid(): boolean {
const invalid = this.children.some(c => !c.IsValid());
return !invalid;
}
需要注意的是children
会后,被定义AfterViewInit
挂钩。
您可以使用组件选择器:
@ViewChildren(ChildComponent) childrenList: QueryList<ChildComponent>;
并循环遍历并确定有效性。
@angular/core
提供了ViewChildren
和QueryList
,可能应该QueryList
您有所帮助。
<child #varName></child>
import { ViewChildren, QueryList } from '@angular/core';
@ViewChildren("varName") customComponentChildren: QueryList<YourComponent>;
this.customComponentChildren.forEach((child) => { let retult = child.IsValid(); })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.