0

I want users to be able to add elements such as user inputs with ionic 2/angular. For example with normal JS I would use this code:

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

how would I go about doing this with ionic2/angularJS?

1
  • As with most things regarding angular, create a model which represents the items. I would think an array would nicely represent a collection of things. Then bind a list of inputs to it using ng-repeat. When the user indicates they want another, add an item to the array. Commented Mar 15, 2017 at 21:55

1 Answer 1

1

In Ionic2/Angular2 you would, in your page/component's template (html), use a ngFor directive to render HTML elements for every item in an array.

In your typescript you can then just push an element to this array and it will be rendered as an extra element of ngFor.

For your code:

in your template:

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

in your typescript:

public items:any[] = [];

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

Definitely have a look at https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

Sign up to request clarification or add additional context in comments.

2 Comments

So this succeeds in generating new input boxes. But the addDestination() function should only generate input boxes NOT store the data. Once all of the input boxes have been filled I need a separate function that stores all of the inputs into an array. Can you please look at this? stackoverflow.com/questions/42808024/…
Oh I see, well, for the model binding this is the easiest approach by far. Can't you use the data structure from the example above as an input for the real save method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.