Как получить доступ к formControlName вложенной FormGroup внутри FormArray - PullRequest
0 голосов
/ 06 июня 2019

Я могу быть совершенно не прав в том, как я управляю формой и информацией здесь.Если так, то извините всех, но я здесь немного потерялся ...

Вот моя форма:

private tpForm = this.fb.group({
    name: [null, Validators.required],
    vat: [null, Validators.required],
    activityNumber: [null],
    addresses: this.fb.array([
      this.createAddress()
    ])
  });

  constructor(private fb: FormBuilder) { }

  createAddress(): FormGroup {
    return this.fb.group({
      street: [null, Validators.required],
      streetComp: [null],
      streetComp2: [null],
      city: [null, Validators.required],
      cp: [null, Validators.required],
      state: [null],
      country: [null, Validators.required]
    });
  }

важное примечание:

  1. форма закрыта
  2. там есть конструктор

, потому что он исходит от службы, которая генерирует форму , котораяадаптирован под разные модели.Но вы получите представление об общей структуре формы.

Моя цель - иметь возможность добавить более одного address, если необходимо, и каждый address является FormGroup объектом, потому что он сам по себе является своего рода формой.

дело в том, что я не могу получить доступ к элементам управления, включенным в FormGroup, сама вложенная в FormArray:

<mat-card-content>
      <mat-grid-list cols="3" rowHeight="1.2:1">
        <form [formGroup]="tpForm" (ngSubmit)="onSubmit()">
        <mat-grid-tile formGroupName="tpForm"> //<--- Here I'm trying to divide the access to the controls (name, vat, activityNumber) this one gives me an error (see below)
            <mat-form-field appearance="outline">
              <mat-label>Customer VAT Number</mat-label>
              <input matInput formControlName="vat">
              <mat-error *ngIf="tpForm.get('vat').invalid">Please enter a VAT number!</mat-error>
              <mat-icon matSuffix *ngIf="tpForm.get('vat').valid || !editing">sentiment_very_satisfied</mat-icon>
              <mat-hint>Customer's local VAT number</mat-hint>
            </mat-form-field>
            <button style="margin: 0.5rem;" mat-raised-button type="button" color="accent" (click)="onLoadInfo()" [disabled]="tpForm.get('vat').invalid || !editing">Load information</button>
            <mat-form-field appearance="fill">
              <mat-label>Customer name</mat-label>
              <input matInput formControlName="name">
              <mat-error *ngIf="tpForm.get('name').invalid">Please enter the customer's name</mat-error>
              <mat-icon matSuffix *ngIf="tpForm.get('name').valid || !editing">sentiment_very_satisfied</mat-icon>
              <mat-hint>Has to match the customer full legal name</mat-hint>
            </mat-form-field>
            <mat-form-field appearance="fill">
              <mat-label>Customer Activity Reference</mat-label>
              <input matInput formControlName="activityNumber">
              <mat-icon matSuffix *ngIf="tpForm.get('activityNumber').value">sentiment_very_satisfied</mat-icon>
              <mat-hint>Customer's local activity reference (INSEE, CNAE...)</mat-hint>
            </mat-form-field>
          </mat-grid-tile>
          <mat-grid-tile formGroupName="tpForm.get('addresses')[0]">//<--- So that I can get the controls from the addresses here 
            <mat-form-field appearance="fill">
              <mat-label>Street</mat-label>
              <input matInput formControlName="street">
              <mat-icon matSuffix *ngIf="tpForm.get('addresses')[0].get('street').value">sentiment_very_satisfied</mat-icon>
              <mat-hint>Customer's local activity reference (INSEE, CNAE...)</mat-hint>
           </mat-form-field>
         </mat-grid-tile>
       </form>
  </mat-grid-list>
</mat-card-content>

Пока что я не слишком удивленоб этом.Все это приводит к следующей ошибке:

ERROR Error: Cannot find control with name: 'tpForm'

Указание на строку в моем коде (см. Комментарий) <mat-grid-tile formGroupName="tpForm">

Я немного потерян в переводе и буду радваш вклад в то, как справиться с этим.Большое спасибо заранее!

Ответы [ 2 ]

2 голосов
/ 06 июня 2019
<form [formGroup]="tpForm" (ngSubmit)="onSubmit()">
    <mat-grid-tile formGroupName="tpForm"> 

Это неправильно, поскольку у вас нет какой-либо группы форм с именем "tpForm" внутри основной группы форм с именем "tpForm".Уберите это бесполезное formGroupName="tpForm".

formGroupName="tpForm.get('addresses')[0]"

Это тоже неправильно.tpForm.get () возвращает элемент управления формы.Вы должны передать имя группы форм formGroupName.

Вам нужно что-то вроде

<div formArrayName="addresses"> <!-- addresses is the name of the form array inside the owning form group tpForm -->
    <div [formGroupName]="0"> <!-- 0 is the index of form group inside the owning form array addresses -->
        <input formControlName="street"> <!-- street is the name of the form control inside the owning form group 0 -->
1 голос
/ 06 июня 2019

Вы пытаетесь получить доступ к члену 'tpForm', который находится внутри вашей FormGroup.который не имеет этого.

 this.fb.group({
**tpForm : this.fb.group({}),** //if you had this it would work.
name: [null, Validators.required],
vat: [null, Validators.required],
activityNumber: [null],
addresses: this.fb.array([
  this.createAddress()
])

});

Вы должны понимать, что без скобок formGroupName = "string" angular считает, что ввод является простой строкой.С помощью скобок [formGroupName] = "objectFromComponent" angular будет считать, что входные данные поступают от объекта-компонента.

Для FormArray я бы посоветовал проверить угловые направляющие, которые очень хорошо объясняют, чего вы хотите достичь.https://angular.io/guide/reactive-forms#step-2-defining-a-formarray-control

...