动态添加/删除Angular2表单的控件

时间:2016-09-25 02:40:48

标签: forms angular typescript

我有一个angular2-final表单,使用* ngFor指令可变数量的复选框输入。这似乎工作正常,只要在ngOnInit中设置一次复选框的数量。但是,我需要能够动态添加/删除复选框,而且我不知道该怎么做。

需要使用哪些组件逻辑才能在运行中从模型驱动的表单中添加/删除输入,如下所示?

示例表单代码:

<form [formGroup]="editProjectForm" (ngSubmit)="edit()" *ngIf="!isLoading">
  <div class="form-group">
    <label class="hero-form-label" for="name">Name</label>
    <input class="form-control" type="text" name="name" formControlName="name">
  </div>
  <div class="form-group">
    <label class="hero-form-label" for="description">Description</label>
    <input class="form-control" type="text" name="description" formControlName="description">
  </div>

  <label class="hero-form-label">Members</label>
  <table class="table table-bordered table-striped">
  <thead class="thead-default">
    <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Email Address</th>
    <th>Include</th>
  </tr>
</thead>
<tbody *ngIf="project?.members === 0">
  <tr>
    <td colspan="4">This project has no members.</td>
  </tr>  
</tbody>
<tbody>
  <tr *ngFor="let user of users">
    <td>{{user.firstName}}</td>
    <td>{{user.lastName}}</td>
    <td>{{user.email}}</td>
    <td>
      <input type="checkbox" name="{{user.id}}" value="{{user.id}}" value="{{ project.hasUser(user.id) }}">
      </td>
    </tr>  
  </tbody>
</table>

1 个答案:

答案 0 :(得分:1)

查看您的模板我不确定您在哪里添加可变数量的复选框,除非您指的是users循环。

回答您的确切问题:

  

需要哪些组件逻辑才能使输入成为可能   从模型驱动的表单添加/删除?

您需要的是https://stackoverflow.com/users/5753091/mohammadreza-khalifeh课程。它可以包含可变数量的控件,它们应该能够解决您的用例。您可以将*ngFor与FormArray一起使用。

您的模型驱动形式可能如下所示:

editProjectForm = new FormGroup({
  name: new FormControl(''),
  description: new FormControl(''),
  users: new FormArray([
    new FormGroup({
      firstName: new FormControl(''),
      lastName: new FormControl(''),
      email: new FormControl(''),
      options: new FormArray([
        new FormGroup({
          type: new FormControl('Project Has User'),
          value: new FormControl(false)
        })
      ])
    })
  ])
});

FormArray有一个绑定FormArray的例子。

相关问题