Formarray угловой простой пример - PullRequest
0 голосов
/ 02 мая 2019

Я новичок в угловой. Я пытаюсь добавить формат для динамического отображения элементов управления формы с помощью formArray. Я попробовал пример angular.io , он работал как сказано, но я пытаюсь добавить к нему больше полей, но столкнулся с какими-то трудностями.

Мой компонент.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>

Как ни странно, html-поля для formArray не отображаются в шаблоне, а вместо этого отображаются значения формы. Я использовал «registrationForm.value | json» для отображения значений формы, напечатанных, как показано ниже

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

Кто-нибудь, пожалуйста, объясните простым примером? Благодаря.

1 Ответ

0 голосов
/ 03 мая 2019

В вашей форме нет свойства contactList, которое необходимо использовать, как показано ниже

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