簡體   English   中英

基於迭代的子組件驗證父組件

[英]Validate parent component based on iterated children components

我有一個父組件,在模板中,我有一個生成子組件的 ngFor。 在這個父模板中,我有一個提交按鈕,在所有生成的子組件的驗證都為真之前,該按鈕應該被禁用。 我的意思是,在子組件中,我應該驗證 3 個字段,並且在所有子組件都有效之后,應該啟用父組件中的提交按鈕。

父組件.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]
      });
   }
}

實現這一目標的最佳實踐是什么?

好問題。 您需要一個表單數組,它跟蹤子表單組的 state:

跟蹤 FormControl、FormGroup 或 FormArray 實例數組的值和有效性 state

以上摘自 angular 文檔: https://angular.io/api/forms/FormArray#description

在你的情況下,這看起來像這樣

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

然后可以通過表單數組上的.valid屬性訪問表單數組的有效 state:

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM