3

我正在做一个项目,我想在表单数组字段上进行所需的验证。这是我的模板

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

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

4

1 回答 1

6

你非常接近答案。price 数组由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 来返回formArrayfor 绑定

get price() {
  return this.vehicleForm.get('prices.price') as FormArray;
}
于 2018-10-08T00:33:41.520 回答