@Romanuss

FormArray не работает?

Здравствуйте, имееться код (компонент, штмл).

import { Component, OnInit } from '@angular/core';
import { PlacesService } from '@Services/places.service';
import { BookingService } from '@Services/booking.service';
import { FormBuilder, FormControl, FormArray, FormGroup} from '@angular/forms';
import { NavigationService } from '@Services/navigation.service';

@Component({
  selector: 'app-entertainment-settings',
  templateUrl: './entertainment-settings.component.html',
  styleUrls: ['./entertainment-settings.component.scss']
})
export class EntertainmentSettingsComponent implements OnInit {
  public invoiceForm: FormGroup;

  public list = [1];

  constructor(
    private placesService: PlacesService,
    private bookingService: BookingService,
    private navigationService: NavigationService,
    private _fb: FormBuilder
  ) { }

  ngOnInit() {
    this.invoiceForm = this._fb.group({
      itemRows: this._fb.array([this.initItemRows()])
    });
  }

  get formArr():  FormArray  {
    return this.invoiceForm.get('itemRows') as FormArray;
  }

  initItemRows() {
   return this.invoiceForm = new FormGroup({
      name: new FormControl('Test ticket name'),
      description: new FormControl('Test description'),
      full_price: new FormControl(100),
      booking: new FormControl() 
    });
}

addNewRow() {
    const control = <FormArray>this.invoiceForm.controls['itemRows'];
    control.push(new FormControl(this.initItemRows()));
}

deleteRow(index: number) {
    const control = <FormArray>this.invoiceForm.controls['itemRows'];
    control.removeAt(index);
}

  public OnSubmit()
  {
    this.addPlace();
  }
  



  public addPlace()
  {
    var data = JSON.parse(localStorage.getItem("placeForm"));

    this.placesService.createPlace(data)
        .subscribe(result => {
            this.addBooking(result.id)
        });
  }

  public addBooking(id: number)
  {
    var data = {
      type: JSON.parse(localStorage.getItem('placeForm')).type,
      place: id
    }


      this.bookingService.createBooking(data).
      subscribe(result => {
          this.invoiceForm.value.booking = result.id,
          this.addBookingOption();
      });
  
  }

  public addBookingOption()
  {
    this.bookingService.createBookingOptions(this.invoiceForm.value).
    subscribe(result => {
         console.log(result);
         localStorage.removeItem("placeForm");
         this.navigationService.navigate(`Places`, false);
    });
  }
}

html

<code lang="javascript">

  <div class="container">
        <div class="row">
            <div class="col-sm-12 col-md-8 col-lg-4">

                <form [formGroup]="invoiceForm">
                <div formArrayName="itemRows">
                    <b>Prices and Availability</b>
                    <div class="row"  *ngFor="let itemrow of formArr.controls ; let i=index"  
                    [formGroupName]="i">
                        <div class="col-12">
                            <input
                                class="form-control"
                                placeholder="Ticket Name"
                                formControlName="name"/>
                        </div>
                        <div class="col-12">
                            <textarea
                                class="form-control"
                                placeholder="Description"
                                formControlName = "description"></textarea>
                        </div>
                        <div class="col-sm-12 col-md-6">
                                <input
                                class="form-control"
                                placeholder="Full Ticket Price"
                                formControlName="full_price"/>
                        </div>
                        <div class="col-sm-12 col-md-6 text-right text-secondary">
                            Discounted $90<br>
                            You will receive $81
                        </div>
                    </div>
                </div>
                    <p>
            <button class="btn btn-primary add-button" *ngIf="formArr.controls.length > 1" 
                (click) ="deleteRow(i)">Remove options</button>
        </p>
                </form>
            </div>
        </div>
    </div>
<div>
    <p>
        <button class="btn btn-primary add-button" (click) ="addNewRow()">Add more options</button>
    </p>
</div>
<app-package></app-package>

<button class="btn btn-primary save-button"
        (click)="OnSubmit()">Save</button>
</code>

При попытке срабатывания кнопки Add more options получаю ошибку ERROR TypeError: Cannot read property 'controls' of null

Хотя всё делаю по правилам FormArray. А именно, через геттер беру значение formArr.controls. В чём может быть проблема?
  • Вопрос задан
  • 87 просмотров
Решения вопроса 1
@svatoy
initItemRows() {
   return new FormGroup({
      name: new FormControl('Test ticket name'),
      description: new FormControl('Test description'),
      full_price: new FormControl(100),
      booking: new FormControl() 
    });
}

addNewRow() {
    const control = <FormArray>this.invoiceForm.get('itemRows');
    control.push(this.initItemRows());
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы