动态添加表单字段后的Angular2日志值

时间:2016-06-19 00:07:22

标签: forms typescript angular angular2-forms

我正在尝试控制日志中选择数组中每个对象的值。我目前能够在choices数组中记录对象,但所有值都是空的。我看到每个对象timeZonePicker: "", startTimeInput: "", endTimeInput: ""。我能够从选择数组中添加和删除并记录密钥,但我无法记录该值。我尝试了很多不同的东西,但仍然没有成功。

<div class="container">
    <div class="row">
        <div class="col-md-9">
            <div *ngFor="let choice of choices; trackBy=customTrackBy" class="form-inline">
                <select [ngModel]="choice.timeZonePicker" class="form-control" id="timeZonePicker">
                    <option *ngFor="let timeZone of timeZones" [selected]="timeZone.chosenTimeZone == '(GMT) Western Europe Time, London, Lisbon, Casablanca, Greenwich'">{{ timeZone.chosenTimeZone }}</option>
                </select>
                    <input [ngModel]="choice.startTimeInput" type="time" class="form-control" id="startTimeInput">
                    <input [ngModel]="choice.endTimeInput" type="time" class="form-control" id="endTimeInput">
            </div> <!-- end form field div -->
            <div class="container">
                <button (click)="onSubmit()" class="btn btn-primary">Submit</button>
            </div>
            <div class="container">
                <button class="pull-left btn btn-success" (click)="addNewChoice()">Add Field</button>
                <button class="pull-left btn btn-danger" (click)="removeChoice()">Remove Field</button>
            </div>
        </div> <!-- end col-md-9 -->
    </div> <!-- end row -->
</div> <!-- end container -->

以下是组件。

export class TimeZonesComponent {
constructor(){}

timeZones = [ 
        { val: -12, chosenTimeZone: '(GMT -12:00) Eniwetok, Kwajalein'},
        { val: -11, chosenTimeZone: '(GMT -11:00) Midway Island, Samoa'},....];

choices = [
    {
    timeZonePicker: '',
    startTimeInput: '',
    endTimeInput: ''
    }, 
    {         
    timeZonePicker: '',
    startTimeInput: '',
    endTimeInput: ''
    }];

addNewChoice(){
    var dataObj = {           
        timeZonePicker: '',
        startTimeInput: '',
        endTimeInput: ''
    };
    this.choices.push(dataObj);
}

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

onSubmit(){  
    console.log(this.choices);  
}

customTrackBy(index: number, obj: any){
    return index;
}
}

我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:0)

我发现了我的错误。我需要使用trackBy(我最初没有)和[(ngModel))。我只使用单向绑定,但我需要两种方式。如果有人想看到学习的代码,只需评论,我很乐意分享。

相关问题