【问题标题】:Angular2 log values after dynamically adding form fields动态添加表单字段后的Angular2日志值
【发布时间】:2016-10-20 12:58:10
【问题描述】:

我正在尝试控制台记录选择数组中每个对象的值。我目前能够在选择数组中记录对象,但所有值都是空的。我看到每个对象都有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;
}
}

非常感谢任何帮助。

【问题讨论】:

    标签: forms typescript angular angular2-forms


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 2013-08-24
      • 2011-09-02
      • 1970-01-01
      • 2016-08-26
      • 2019-04-19
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多