Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Adding new <li> item onClick event

Tags:

angular

I use *ngFor iterating an array in order to show them in a list, but i can't add a new item in my list. During Onclick Event i get an empty li. Probably i am not linking correct something? A directive? or what? Maybe i use a wrong variable?

My exporting class where i have my constructor:

export class ContactInfo {
    constructor( public description:string) { }
}

i load the above class in my app.component.ts and the code follows. I use templateUrl where my main html exists (you can see it at the 3rd code part).

import {Component} from 'angular2/core';
import {ContactInfo} from './contactinfo';
@Component({
   selector: 'my-app',
   templateUrl: 'app/app.component.html'
 })
export class AppComponent { 

    title = 'Angular App';
    name = "Fotis";
    lastName = "Karalis";
    myTitle = 'Web Developer';
    information = [
      new ContactInfo('HTML5 = Regards DOM'),
      new ContactInfo('CSS3 = Regards DOM styling')
    ];
    myInfo = this.information[0];
    addInfo(newInfo:string) {
      if (newInfo) {
        this.information.push(newInfo);
      }
    }
 }

And my main app.component html is:

<h1>Project: {{title}}</h1>
<span>{{name}}</span>
<span>{{lastName}}</span>
<a href="#">Position: {{myTitle}}</a>
<h4>Skills</h4>
<ul>
  <li *ngFor="#info of information">
   <pre>{{ info.description }} </pre>
  </li>
</ul>

<input #newInfo
  (keyup.enter)="addInfo(newInfo.value)"
  (blur)="addInfo(newInfo.value); newInfo.value='' ">

<button (click)=addInfo(newInfo.value)>Add</button>
like image 581
FotisK Avatar asked Feb 15 '16 17:02

FotisK


2 Answers

here is working demo for your problem:

http://plnkr.co/edit/fictP28Vqn74YqrwM1jW?p=preview

Just changed your method like this:

addInfo(newInfo:string) {
    if (newInfo) {
        this.information.push(new ContactInfo(newInfo));
    }
  }

you have not created a new instance for the exported class ContactInfo because of this your string is not properly pushing in the array.

like image 123
Pardeep Jain Avatar answered Nov 09 '22 05:11

Pardeep Jain


When you add

this.information.push(newInfo); 

You don't add ContactInfo instance but string which doesn't have description property.

like image 4
kit Avatar answered Nov 09 '22 06:11

kit