Angular 4 フォーム FormArray フォーム入力行を追加・削除するボタンを追加する。

Angular 4.0.2を使ってアプリを作成しています。フォームに新しい入力の行を追加するためのボタンと、特定の行を削除するための削除ボタンを追加するにはどうすればよいでしょうか?つまり、私はこのようなフォームが欲しいのです。私はフォームをこのようなものにしたいのです:

!"フォーム画像"1です。

以下は私のコードです:

アドインボイスコンポーネント.html

    <h3 class="page-header">Add Invoice</h3>
    <form [formGroup]="invoiceForm">
      <div formArrayName="itemRows">
        <div *ngFor="let itemrow of itemRows.controls; let i=index" [formGroupName]="i">
          <h4>Invoice Row #{{ i + 1 }}</h4>
          <div class="form-group">
            <label>Item Name</label>
            <input formControlName="itemname" class="form-control">
          </div>
          <div class="form-group">
            <label>Quantity</label>
            <input formControlName="itemqty" class="form-control">
          </div>
          <div class="form-group">
             <label>Unit Cost</label>
             <input formControlName="itemrate" class="form-control">
          </div>
          <div class="form-group">
            <label>Tax</label>
            <input formControlName="itemtax" class="form-control">
          </div>
          <div class="form-group">
            <label>Amount</label>
            <input formControlName="amount" class="form-control">
          </div>
          <button *ngIf="i > 1" (click)="deleteRow(i)" class="btn btn-danger">Delete Button</button>
        </div>
      </div>
      <button type="button" (click)="addNewRow()" class="btn btn-primary">Add new Row</button>
    </form>
    <p>{{invoiceForm.value | json}}</p>

以下は、add-invoice.component.tsのコードです。

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormArray, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-add-invoice',
  templateUrl: './add-invoice.component.html',
  styleUrls: ['./add-invoice.component.css']
})

export class AddInvoiceComponent implements OnInit {
  invoiceForm: FormGroup;

  constructor(
    private _fb: FormBuilder
  ) {
    this.createForm();
  }

  createForm(){
    this.invoiceForm = this._fb.group({
      itemRows: this._fb.array([])
    });
    this.invoiceForm.setControl('itemRows', this._fb.array([]));
  }

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

  addNewRow(){
    this.itemRows.push(this._fb.group(itemrow));
  }

  ngOnInit(){

  }
}
質問へのコメント (8)
ソリューション

以下は、あなたのコードを短くしたものです:

フォームを初期化する際に、formArrayの中に空のformgroupを1つ追加することができます:

解説 (11)