2017-03-15 26 views
0

我希望用戶能夠使用ionic 2/angular添加用戶輸入等元素。例如與正常的JS我會使用此代碼:如何在ionic2/angularJS中動態添加元素

function addDestination(){ 
     var destDiv = document.getElementById('destPlaceholder'); 
     destDiv.innerHTML += '<ul class="rounded"><li><input type="text" class="node" placeholder="text" id="d" /></li></ul>'; 
    } 

我將如何去做這與ion2/angularJS?

+0

與關於角大多數事情一樣,創建一個代表項目的模型。我認爲一個數組很好地代表了一系列事物。然後使用'ng-repeat'將輸入列表綁定到它。當用戶指出他們想要另一個時,將一個項目添加到數組中。 –

回答

1

在Ionic2/Angular2中,您可以在頁面/組件的模板(html)中使用ngFor指令爲數組中的每個項目呈現HTML元素。

在您的打字稿中,您可以將一個元素推送到此數組中,並將其作爲ngFor的額外元素呈現。

爲您的代碼:

在你的模板

<ul class="rounded"> 
    <li *ngFor="let item from items"> 
     <input type="text" class="node" placeholder="{{item.someattribute}}" id="{{item.id}}" /> 
    </li> 
</ul> 
在您的打字稿

public items:any[] = []; 

addDestination() { 
    this.items.push({id: 1, text: "the item's text"}); 
} 

絕對看看https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

+0

因此,這成功地生成新的輸入框。但addDestination()函數應該只生成不存儲數據的輸入框。一旦所有的輸入框都填滿了,我需要一個單獨的函數將所有的輸入存儲到一個數組中。你能看看這個嗎? http://stackoverflow.com/questions/42808024/how-to-generate-fields-and-store-user-inputs-into-an-array-ionic2 – Dansmith12

+0

哦,我看,嗯,模型綁定這是最簡單的到目前爲止。難道你不能使用上面例子中的數據結構作爲實際保存方法的輸入嗎? – nickscheynen