反应形式:模式验证不适用于子组件

时间:2019-06-03 06:00:27

标签: angular angular-reactive-forms reactive-forms

演示代码 https://stackblitz.com/edit/angular-yaipfv

在上面的示例中,我有一个带有嵌套表单组的反应式表单.address-form子组件用于嵌套表单组。验证是在父组件中完成的,除了模式验证之外,所有工作似乎都有效。< strong>对必填项的验证工作正常,但模式验证无效。

我使用了validators.compose将所需的验证和模式验证结合在一起。在这里我做错了什么吗?

父组件表单构建

 this.form = this.fb.group ({
  phone: ['123-456-1234'],
  fax: [null],
  email: [null],
  website: [null],
  editUserForm_Address : this.fb.group ({
    address1: 
   [null,Validators.compose([Validators.pattern('[0-9] 
   {16}'), Validators.required])],
    address2: [null],
    city: ['Dummy City', Validators.required],
    state: ['Dummy State', Validators.required],
    zipcode: ['11111', Validators.required],
    country: ['USA', Validators.required]
   })
   });

父HTML

<form [formGroup]="form">
  <address-form [formGroup]="form.get('editUserForm_Address')"></address-form>
  <button type="submit">Submit</button>
</form>

<pre>{{ form.value | json  }}

子组件HTML

<div [formGroup]="formGroup">   
  <div class = "row">
    <div
      class="form-group col-12"
      [ngClass]="{'error': (formGroup.get('address1').errors)}">
      <label for="street" >Address 1*</label>
      <input
        placeholder="Address 1"
        class="form-control"
        formControlName="address1" />
      <div *ngIf="(formGroup.get('address1').errors)" class="error-msg">
        <div [hidden]="!formGroup.get('address1').errors.required"
class = "input_feedback">Address 1 is required.</div>
 <div [hidden]="!formGroup.get('address1').errors.pattern"
class = "input_feedback">Address should follow the pattern</div>
      </div>

    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

对于我来说,您是验证模式,请输入:loopy。 您想验证哪种信息?) 您也可以将其替换为

1234567890123456