2016-09-25 81 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