使用类进行表单数组验证

时间:2018-04-23 08:47:54

标签: angular angular-reactive-forms

我有已实现的表单数组的表单但在这里我无法验证基本上我不知道如何从表单数组获取控件。我有一个错误控制未定义。

在这里你可以看到我的代码我尝试了什么

<form [formGroup]="myForm">

    <div formArrayName="addresses" >
        <div *ngFor="let address of myForm.controls.addresses.controls; let i=index" class="panel panel-default">

            <div [formGroupName]="i" class="myform">
                <label>street</label>
                <input type="text" class="form-control" formControlName="street" [class.valid]="address.street.valid"><br><br>
                <label>postcode</label>
                <input type="text" class="form-control" formControlName="postcode">
            </div><br><br>
        </div>
    </div><br><br>
        <pre>form value: <br>{{myForm.value | json}}</pre>
</form>

你可以在这里看到完整的工作示例

https://stackblitz.com/edit/angular-r4jruv?file=app%2Fapp.component.html

3 个答案:

答案 0 :(得分:1)

首先,在您的组件中添加一个getter,以缩短FormArray控件的访问路径。

<强> component.ts

fa: FormArray;

ngOnInit() {
  const fa = this._fb.array([
    this.initAddress(),
  ]);

  this.fa = fa;

  this.myForm = this._fb.group({
    addresses: fa
  });
}

接下来,更新html

<强> component.html

<div *ngFor="let address of fa.controls; let i=index" class="panel panel-default">
  <div [formGroupName]="i" class="myform">
    <label>street</label>
    <input type="text" class="form-control" formControlName="street" [class.valid]="address.valid"><br><br>
  </div>
</div>

Live demo

答案 1 :(得分:0)

您是直接从street访问address,但它实际上位于address.controls

<form [formGroup]="myForm">

<div formArrayName="addresses" >
    <div *ngFor="let address of myForm.controls.addresses.controls; let i=index" class="panel panel-default">

        <div [formGroupName]="i" class="myform">
            <label>street</label>
            <input type="text" class="form-control" formControlName="street" [class.valid]="address.controls.street.valid"><br><br>
            <label>postcode</label>
            <input type="text" class="form-control" formControlName="postcode">
        </div><br><br>
    </div>
</div><br><br>
    <pre>form value: <br>{{myForm.value | json}}</pre>
</form>

这应该有效

答案 2 :(得分:0)

您可以使用表单控件状态:

<input ... [class.valid]="address.status === 'VALID'">

Here is an edit of your stackblitz.