【问题标题】:Angular get status of all children components from parent componentAngular从父组件获取所有子组件的状态
【发布时间】:2019-03-14 06:51:00
【问题描述】:

我有组件“父”和“子”。从父我们可以添加或删除子。所以孩子是动态的。在 Parent 中,我已经在循环中渲染了 Child 组件,如下所示

父组件.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
}

在父组件中,我有一个名为“保存”的按钮,如果所有子组件都有效,则必须启用该按钮,否则需要禁用该按钮。

所以我需要一种方法来从 Parent 中为每个子组件调用 Child 组件 IsValid 函数,然后确定有效性结果并将其应用于 Save 按钮以启用或禁用

我的尝试

1. 我已经从孩子向父母发出了有效或无效的结果,如果任何孩子的结果无效,我已经禁用了保存按钮。

但这里的问题是:如果我添加了一个孩子,使其有效,保存按钮将被启用。现在我添加了另一个无效的孩子,因此保存按钮将被禁用,但如果我删除无效的孩子,保存按钮将被禁用,尽管我们只有一个有效的孩子..因为 IsValid 事件只有在当前孩子发生变化时才会被触发。

2. 我可以使用这样的东西

<child #varName></child>

@ViewChild('varName') childElement;

然后我可以从父母那里打电话

childElement.IsValid() 

但是因为我已经在循环中渲染了孩子,所以如何在循环中给出唯一名称以及如何在 ts 文件中添加对该唯一 HTML 标记的引用。

我在这里创建了案例SlackBlitz

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 请尝试创建一个(最小的)StackBlitz 来展示问题。
  • 如果您使用的是表单组,那么每当您向其中添加孩子时,您都可以轻松检查它的状态,或者我建议使用反应式表单
  • @Jeto 在给定的 URL 创建了案例 .. 更新了问题 .. 谢谢

标签: javascript angular


【解决方案1】:

您可能想使用@ViewChildren

在你的父组件中:

@ViewChildren(ChildComponent) children: QueryList<ChildComponent>;

areChildrenValid(): boolean {
   const invalid = this.children.some(c => !c.IsValid());
   return !invalid;
}

注意children 将在AfterViewInit 钩子之后定义。

【讨论】:

    【解决方案2】:

    @angular/core 提供了ViewChildrenQueryList,可能对你有帮助。

    <child #varName></child>
    import { ViewChildren, QueryList } from '@angular/core';
    @ViewChildren("varName") customComponentChildren: QueryList<YourComponent>;
    
    this.customComponentChildren.forEach((child) => { let retult = child.IsValid(); })
    

    【讨论】:

      【解决方案3】:

      你可以使用组件选择器:

      @ViewChildren(ChildComponent) childrenList: QueryList<ChildComponent>;
      

      并通过它运行一个循环并确定有效性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 2019-11-27
        • 2020-08-19
        • 2019-05-12
        • 2020-11-13
        • 1970-01-01
        相关资源
        最近更新 更多