2016-06-18 107 views
3

我试图动态添加字段到选择数组时addNewChoice被点击,但仍然不成功。Angular2动态添加/删除表单域

<form class="form-inline"> 
    <fieldset *ngFor="let choice of choices"> 
     <div class="form-group">   
      <select class="form-control" id="timeZonePicker"> 
       <option value="-12" >(GMT -12:00) Eniwetok, Kwajalein</option> 
       <option value="-11" >(GMT -11:00) Midway Island, Samoa</option> 
        ............ 
      </select> 
     </div> 
     <div class="form-group"> 
      <input type="time" class="form-control" id="startTimeInput"> 
     </div> 
     <div class="form-group"> 
      <input class="time" class="form-control" id="endTimeInput"> 
     </div> 
    </fieldset> 
</form> 
    <button class="pull-left btn btn-success" (click)="addNewItem()">Add Field</button> 
    <button class="pull-left btn btn-danger" (click)="removeItem()">Remove Field</button> 

这里是组件。

export class TimeZonesComponent { 
constructor(){} 

choices = [{id: 1}, {id: 2}]; 

addNewChoice(){ 
    var newItemNo = this.choices.length + 1; 
    this.choices.push({'id': newItemNo}); 
} 

removeChoice(){ 
    var lastItem = this.choices.length - 1; 
    this.choices.splice(lastItem); 
}} 

我已经尝试了一堆不同的Angular.js解决方案在这里,但没有与Angular2运气。任何帮助深表感谢!

+1

为什么你的方法被称为'addNewItem'和'removeItem'但在你的组件使用了'addNewChoice'和'removeChoice'? – yurzui

+0

我在看一个不同的例子,并且意外地使用了他们使用的名字。将其更改为正确的名称!万分感谢!!! – joaoSaulo

+0

@yurzui我有一个问题。如何在类中访问动态添加的表单域(例如,在上面的示例TimeZonesComponent类中)? –

回答

0

没有像addNewItem和removeItem这样的函数。

<button class="pull-left btn btn-success" (click)="addNewChoice()">Add Field</button> 
    <button class="pull-left btn btn-danger" (click)="removeChoice()">Remove Field</button> 
+0

如何在类中访问动态添加的表单域(例如,在上面的示例TimeZonesComponent类中)? –

+0

你是什么意思? – NEER