动态字段的Angular 2表单验证

时间:2017-09-25 16:50:06

标签: angular angular2-forms

我正在开发一个Angular 4.X项目,我正在点击按钮创建一些HTML输入字段(大多数是文本类型)。动态创建输入框工作正常,但我无法对这些字段实施验证。我收到以下错误。

无法阅读财产'无效' of null(...)

我为此创造了一个插件。以下是我创建的插件的链接 -

https://plnkr.co/edit/PCFD43GK91zo2ivQ9lf7?p=preview 为便于参考,请找到以下代码 -

//Root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `<hr>
              <div>  
                <form [formGroup]="orderForm" (ngSubmit)="OnSubmit(orderForm.value)">
                  <div>
                    <input type="text" formControlName="customerName"/>
                    <input type="text" formControlName="email"/>
                  </div>
                  <div formArrayName="items" *ngFor="let item of items.controls; let i = index;">
                    <div [formGroupName]="i">
                      <input type="text" formControlName="name" placeholder="Item name"/>
                      <small *ngIf="IsValidField('name')" class="text-danger">
                        Name is required
                      </small>
                      <input type="text" formControlName="description" placeholder="Item description"/>
                      <small *ngIf="IsValidField('description')" class="text-danger">
                        Description is required
                      </small>
                      <input type="text" formControlName="price" placeholder="Item price"/>
                      <small *ngIf="IsValidField('price')" class="text-danger">
                        Price is required
                      </small>
                    </div>
                    Chosen name: {{ orderForm.controls.items.controls[i].controls.name.value }}
                  </div>
                  <button type="submit">Save</button>
                  <button type="button" (click)="addItem()">Add More</button>
                </form>
              <div>`,
})

export class App {

  constructor(private formBuilder: FormBuilder) {  }

  public orderForm: FormGroup;



  ngOnInit() {
      this.orderForm = this.formBuilder.group({
        customerName: '',
        email: '',
        items: this.formBuilder.array([ this.createItem()])
      });
  }

 createItem(): FormGroup {
    return this.formBuilder.group({
      name: ['',[Validators.required,Validators.maxLength(10)]],
      description: '',
      price: ['',[Validators.required,Validators.pattern("[(0-9)*]")]]
    });
  }

   get items(): FormArray {
    return this.orderForm.get('items') as FormArray;
   };

  addItem(): void {
  this.items.push(this.createItem());
  }

  public OnSubmit(formValue: any) {
        console.log(JSON.stringify(formValue));
    }

    public IsValidField(field: string) {
        return (this.orderForm.get(field).invalid && this.orderForm.get(field).touched) || (this.orderForm.get(field).invalid && this.orderForm);
    }

}

@NgModule({
  imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您正在orderForm内搜索动态添加的表单字段,该字段在此处不可用。您应该在访问其值之前正确查询表单。我在下面绘制了一个图,它将帮助您了解动态创建的表单架构。

orderForm (FormGroup)
  |
  - Items (FormArray)
    |
     - 0 (FormGroup)
       - name 
       - description
       - price
    |
     - 1 (FormGroup)
       - name
       - description
       - price
    |
    |.........

因此IsValidField函数应获取index formArray元素和字段名称。您可以通过它轻松查询表单元素。

public IsValidField(i: number, field: any) {
    var f = this.orderForm
            .get('items') //retrieve items FormArray
            .get(i.toString()) //retrieve items FormGroup
            .get(field); //retrieve items form field
    return (f.invalid && f.touched) || (f.invalid && this.orderForm);
}

然后相应地更改IsValidField上的*ngIf函数调用。

*ngIf="IsValidField(i, 'name')"
*ngIf="IsValidField(i, 'description')"
*ngIf="IsValidField(i, 'price')"

Demo Plunker