简体   繁体   中英

How to i add an elements dynamically in ionic2/angularJS

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM