Angular2 - Adding a new item to an array through ngFor directive

19,141 views
Skip to first unread message

Cool Zebra

unread,
Jun 17, 2016, 9:22:20 AM6/17/16
to AngularJS
I apologize that I'm a complete beginner to angular2.

I have an array with a list of items and a button that allows users to create new items. Upon clicking the button, users will be asked to list a new item. When the user presses enter, the new item will be stored in an array. This array should then be updated in the ngFor directive.

Here is my current code

export class HelloWorld {
 
 
// Declaring the variable for binding with initial value
  yourName
: string = '';
  items
= ["pineapple", "apples", "tomatoes", "water"];
  addItems
() {
    newItem
= prompt("Enter a new item");
    items
.push(this.newItem);
 
}
}


Here is my corresponding view

<button (click)="addItems()">Add Items</button>


<ul>
   
<li *ngFor="#item of items">{{item}}</li>
</ul>


I created a plunker for this


Any help will be greatly appreciated. Thanks in advance.

Sander Elias

unread,
Jun 17, 2016, 9:41:50 AM6/17/16
to AngularJS
HI Zebra,

try this:
 addItems() {
 newItem
= prompt("Enter a new item");

 
this.items.push(this.newItem);
 
}

your code is setting a global items, or throws an error (depending on your config/setup)

Regards
Sander


Cool Zebra

unread,
Jun 17, 2016, 4:22:48 PM6/17/16
to AngularJS
Thanks for your answer.

While this does add a bullet point, it doesn't add the actual value entered.

Sander Elias

unread,
Jun 18, 2016, 1:05:10 AM6/18/16
to AngularJS
Hi,

Are you also new to Javascript? 
Apparently I didn't read the entire code well enough ;)

addItems() {
 let newItem
= prompt("Enter a new item");
 
this.items.push(newItem);
 
}

You really should read up on how to declare and use variables and where this is about in classes

Regards
Sander
Reply all
Reply to author
Forward
0 new messages