【问题标题】:Validate parent component based on iterated children components基于迭代的子组件验证父组件
【发布时间】:2021-06-17 08:55:39
【问题描述】:

我有一个父组件,在模板中,我有一个生成子组件的 ngFor。 在这个父模板中,我有一个提交按钮,在所有生成的子组件的验证都为真之前,该按钮应该被禁用。 我的意思是,在子组件中,我应该验证 3 个字段,并且在所有子组件都有效之后,应该启用父组件中的提交按钮。

parent.component.html

<div *ngFor="let condition of conditions">
   <child-component></child-component>
</div>
.
.
.
<button>Submit</button>

child.component.html

<form [formGroup]="frmGrp">
   <input type="text" formControlName="name" />
   <input type="text" formControlName="address" />
   <input type="text" formControlName="phone" />
</form>

child.component.ts

export class ChildComponent {
   
   frmGrp: FormGroup;

   constructor(private fb: FormBuilder){
      this.frmGrp = this.fb.group({
         name: ["", Validators.required],
         address: ["", Validators.required],
         phone: ["", Validators.required]
      });
   }
}

实现这一目标的最佳做法是什么?

【问题讨论】:

    标签: angular validation formgroups


    【解决方案1】:

    很好的问题。 您需要一个表单数组,它跟踪子表单组的状态:

    跟踪 FormControl、FormGroup 或 FormArray 实例数组的值和有效性状态

    以上是角度文档的摘录:https://angular.io/api/forms/FormArray#description

    在你的情况下,这看起来像这样

    <div formArrayName="conditionsFormArray">
      <div *ngFor="let condition of conditions; let i=index">
      
      </div>
    </div>
    

    那么表单数组的有效状态可以通过表单数组上的.valid属性访问:

     this.conditionsForm = this.fb.group({
          conditions: this.fb.array([]) ,
        });
      
      }
     
      get conditions() : FormArray {
        return this.conditionsForm.get("conditions") as FormArray
      }
    
    conditions.valid // valid state of all form groups here
    

    【讨论】:

      猜你喜欢
      • 2016-05-14
      • 2020-01-30
      • 2017-04-05
      • 2017-08-18
      • 2012-11-14
      • 1970-01-01
      • 2018-08-30
      • 2014-05-18
      • 2014-01-11
      相关资源
      最近更新 更多