2017-03-15 31 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