2016-09-25 85 views
1

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

需要使用什么组件逻辑才能使输入可以在模型驱动的窗体中添加/删除,如下面的动态窗体?

示例表格代码:

<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

看你的模板,我不知道你在哪里添加可变数量的复选框,除非你是指你的users循环。

要回答你的问题相关:

什么组件逻辑是必要让这个输入可以 添加/模型驱动的形式取出?

您需要的是FormArray类。它可以包含可变数量的控件,它们应该能够解决您的使用案例。您可以使用FormArray和*ngFor

你的模型驱动形式可以是这个样子:

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的例子。

+0

能够执行。很棒。 – jrdnmdhl