formarray角简单示例

时间:2019-05-02 20:35:44

标签: angular angular-reactive-forms formarray

我是新手。我正在尝试添加一个formarray以使用formArray动态显示表单控件。 我已经尝试了angular.io示例,但如上所述,但我尝试向其添加更多字段,但发现了某种困难。

我的component.ts

import { FormGroup, FormBuilder, Validators, FormArray } from '@angular/forms';
export class ReactiveFormsComponent implements OnInit {
  public contactList: FormArray;
  constructor(private fb: FormBuilder) { }
  registrationForm = this.fb.group({
     userName: ['',[Validators.required, Validators.minLength(3)]],
     password:[''],
     confirmPassword:[''],
     address: this.fb.group({
      city:[''],
      state:[''],
      postalCode:['']
     }),
     contacts: this.fb.array([this.createContact()])
  });
  createContact(): FormGroup {
    return this.fb.group({
     name: [],
     email: []      
    });
  }
  // add a contact form group
  addContact() {
   this.contactList.push(this.createContact());
  }
  // remove contact from group
  removeContact(index) {
    this.contactList.removeAt(index);
  }
  registrationData = [];
  onSubmit(){
    console.log(this.registrationForm.value);
    this.registrationData.push(this.registrationForm.value);
    this.registrationForm.reset();
  }

  ngOnInit() {
    this.contactList = this.registrationForm.get('contacts') as FormArray;
  }
}

我的component.html:

<div class="container-fluid mb-5">
<h2>Registration Form</h2>

 {{ registrationForm.value | json }}

<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
 <div class="form-group">
  <label>Username</label>
  <input type="text" formControlName="userName" name="userName" class="form-control">
</div>

<div class="form-group">
  <label>Password</label>
  <input type="password" formControlName="password" name="password" class="form-control">
</div>

<div formGroupName="address">
  <div class="form-group">
      <label>City</label>
      <input type="text" formControlName="city" name="city" class="form-control">
    </div>
  ---------
  --------
</div> 

<div formArrayName="contacts" *ngFor="let contacts of registrationForm.controls.contactList; let i = index;" >

    <div [formGroupName]="i" >
      <!-- Contacts Form controls Here -->

        <input type="text" placeholder="name" formControlName="name">
        <input type="text" placeholder="email" formControlName="email">

    </div>

</div>

<button class="btn btn-primary" type="submit">Register</button>

奇怪的是,formArray的html字段未显示在模板中,而是显示了表单值。我使用“ registrationForm.value | json”来显示表单值,如下所示

{ "userName": null, "password": null, "confirmPassword": null, "address": { "city": null, "state": null, "postalCode": null }, "contacts": [ { "name": null, "email": null } ] }

有人请举一个简单的例子吗?谢谢。

1 个答案:

答案 0 :(得分:0)

您的表单中没有名为contactList的属性,您需要按以下方式使用

<div formArrayName=“contacts” *ngFor=“let contact of contactList; let i = index;” >