我試圖動態添加字段到選擇數組時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類中)? –