Angular 5 表单数组字段的表单验证

Angular 5 Form validation on form array fields

我正在从事一个项目,我想在其中对表单数组字段进行必要的验证。 这是我的模板

 <div  formArrayName="price" *ngFor="let p of vehicleForm.get('prices.price').controls; let i=index">
        <div class="price-form-repeater" [formGroupName]="i">

                <div class="col-md-6 col-sm-12 cust-col">
                    <label class="col-sm-4 dark-label" for="priceType">Price Type:</label>
                    <div class="col-md-6" >
                    <select id="priceType" formControlName="type" class="form-control" data-placeholder="select"  >
                        <option ></option><!-- Required for data-placeholder attribute to work with Chosen plugin -->
                        <option value="public">Public</option>
                    </select>

                    <div *ngIf="p.controls.type.errors  && (p.controls['type'].dirty || p.controls['type'].touched)) ||
                    (p.controls['type'].untouched && formSubmitAttempt)"class="alert alert-danger">
                        <div [hidden]="(!p.controls['type'].errors.required)">Price type is required.</div>
                    </div>  
                    </div>
                </div>
        </div>
 </div>

这是我的组件

  prices: this.fb.group({
    price: this.fb.array([this.priceField()]) ,
})

priceField():FormGroup {
  return this.fb.group({
    type: ['',Validators.required],  
    vat_type: ['',Validators.required], 
    currency: ['',Validators.required],  
    negotiable: ['',Validators.required], 
    value: ['',Validators.required],  
    tax_deduction: ['',Validators.required]  
  });
}

我只想在用户试图将这些字段留空时显示必填字段错误消息。感谢您的帮助。

你已经很接近答案了。价格数组由 formGroup 个元素组成,因此需要使用 get('') 访问子控件。 *ngFor 指令必须放在中继器上。我还建议 ngIf 而不是隐藏,因为屏幕阅读器可能仍会读取隐藏的元素。

<div  formArrayName="price" >
  <div class="price-form-repeater" *ngFor="let p of vehicleForm.get('prices.price').controls; let i=index" [formGroupName]="i">
    <div class="col-md-6 col-sm-12 cust-col">
      <label class="col-sm-4 dark-label" for="priceType">Price Type:</label>
      <div class="col-md-6" >
        <select id="priceType" formControlName="type" class="form-control" data-placeholder="select">
          <option ></option><!-- Required for data-placeholder attribute to work with Chosen plugin -->
          <option value="public">Public</option>
        </select>

        <div *ngIf="(p.get('type').errors && (p.get('type').dirty || p.get('type').touched)) || 
      (p.get('type').untouched && formSubmitAttempt)" class="alert alert-danger">
                    <div *ngIf="p.get('type').errors.required">Price type is required.</div>
                </div>  
                </div>
            </div>
    </div>

控制器必须有一个 getter 到 return 的 formArray 用于绑定

get price() {
  return this.vehicleForm.get('prices.price') as FormArray;
}