【问题标题】:Dynamically adding/removing controls to Angular2 form向 Angular2 表单动态添加/删除控件
【发布时间】:2017-02-02 14:51:26
【问题描述】:

我有一个使用 *ngFor 指令的 angular2-final 表单,其中包含可变数量的复选框输入。只要在 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>

【问题讨论】:

    标签: forms angular typescript


    【解决方案1】:

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

    回答您的确切问题:

    需要什么组件逻辑才能使输入可以 从模型驱动的表单中添加/删除?

    您需要的是 FormArray 类。它可以包含可变数量的控件,它们应该能够解决您的用例。您可以将 *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)
            })
          ])
        })
      ])
    });
    

    Angular2 bind array with ngFor 有一个绑定到 FormArray 的示例。

    【讨论】:

    • 能够实现。效果很好。
    猜你喜欢
    • 2016-10-20
    • 2011-01-01
    • 2013-02-26
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多