多次生成formgroup

时间:2018-02-26 07:54:27

标签: angular typescript angular5

我使用angular2反应形式:

this.generateForm = this._fb.group({
      id: [''],
      name: ['']
    });

我有一个按钮“添加”,当我点击它时,我需要重新生成相同的表单,并在html中显示新的表单。我该怎么办?

<form [formGroup]="generateForm">
  <div>
    <label>ID</label>
    <input type="text" formControlName="id">
  </div>
  <div>
    <label>Name</label>
    <input type="text" formControlName="name">
  </div>
  <button (click)="add()"> add </button>
</form>

1 个答案:

答案 0 :(得分:1)

你应该使用FormArray。 请参阅此plunker

<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)">
        <div class="form-group">
          <label>Name</label>
          <input type="text" class="form-control" formControlName="name">
          <small *ngIf="!myForm.controls.name.valid" class="text-danger">
              Name is required (minimum 5 characters).
            </small>
        </div>
        <!--addresses-->
        <div formArrayName="addresses">
          <div *ngFor="let address of myForm.controls.addresses.controls; let i=index" class="panel panel-default">
            <div class="panel-heading">
              <span>Address {{i + 1}}</span>
              <span class="glyphicon glyphicon-remove pull-right" *ngIf="myForm.controls.addresses.controls.length > 1" (click)="removeAddress(i)"></span>
            </div>
            <div class="panel-body" [formGroupName]="i">
              <address [group]="myForm.controls.addresses.controls[i]"></address>
            </div>
          </div>
        </div>

        <div class="margin-20">
          <a (click)="addAddress()" style="cursor: default">
            Add another address +
          </a>
        </div>

        <div class="margin-20">
          <button type="submit" class="btn btn-primary pull-right" [disabled]="!myForm.valid">Submit</button>
        </div>
        <div class="clearfix"></div>

        <div class="margin-20">
          <div>myForm details:-</div>
          <pre>Is myForm valid?: <br>{{myForm.valid | json}}</pre>
          <pre>form value: <br>{{myForm.value | json}}</pre>
        </div>
      </form>