Angular2动态添加/删除表单字段

时间:2016-06-18 05:48:08

标签: forms typescript angular angular2-forms

当点击addNewChoice但仍然不成功时,我正在尝试动态地将字段添加到choices数组中。

<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 个答案:

答案 0 :(得分: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>