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

时间:2018-10-07 19:41:14

标签: angular angular-reactive-forms angular2-form-validation

我正在一个项目中,我希望将所需的验证放在表单数组字段上。 这是我的模板

 <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]  
  });
}

如果用户尝试将这些字段留空,我只想显示必填字段错误消息。我请你帮忙。

1 个答案:

答案 0 :(得分:2)

您非常接近答案。价格数组由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>

控制器必须具有吸气剂才能返回formArray进行绑定

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