我试图动态添加字段到选择数组时addNewChoice被点击,但仍然不成功。Angular2动态添加/删除表单域
<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
我在看一个不同的例子,并且意外地使用了他们使用的名字。将其更改为正确的名称!万分感谢!!! – joaoSaulo
@yurzui我有一个问题。如何在类中访问动态添加的表单域(例如,在上面的示例TimeZonesComponent类中)? –