【问题标题】:Angular2 dynamically adding/removing form fieldsAngular2动态添加/删除表单字段
【发布时间】:2016-10-20 00:11:03
【问题描述】:

当单击 addNewChoice 但仍不成功时,我正在尝试将字段动态添加到选择数组中。

<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 没有运气。非常感谢任何帮助!

【问题讨论】:

  • 为什么你的方法被称为addNewItem和removeItem,但在你的组件中你使用的是addNewChoice和removeChoice?
  • 我在看一个不同的例子,不小心取了他们使用的名字。将其更改为正确的名称有效!非常感谢!!!
  • @yurzui 我有一个问题。如何访问类中动态添加的表单字段(例如,在上面的示例 TimeZonesComponent 类中)?

标签: forms typescript angular angular2-forms


【解决方案1】:

没有像 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>

【讨论】:

  • 如何访问类中动态添加的表单字段(例如,在上面的示例 TimeZonesComponent 类中)?
猜你喜欢
  • 2019-04-19
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 2016-10-20
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
相关资源
最近更新 更多