简体   繁体   中英

Angular2 dynamically adding/removing form fields

I'm trying to dynamically add fields to the choices array when addNewChoice is clicked but still unsuccessful.

<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>

Here is the component.

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);
}}

I've tried a bunch of different Angular.js solutions on here but no luck with Angular2. Any help is much appreciated!

No function like addNewItem and 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM