Angular2 - adding a new <li> onClick event element

I am using * ng parsing an array to show them in a list, but I cannot add a new item to my list. During the Onclick event, do I get empty. I guess I'm not tying something right? Directive? or what? Maybe I'm using the wrong variable?

My export class, where I have my constructor:

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

Download the above class in my app.component.ts and this code follows it. I use templateUrl where my main html exists (you can see it on the third part of the code).

 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:

 <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> 
+5
source share
2 answers

here is a working demonstration of your problem:

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

Just changed my method as follows:

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

You did not create a new instance for the exported class ContactInfo , because of this, your string does not insert the array correctly.

+8
source

When you add

 this.information.push(newInfo); 

You are not adding an instance of ContactInfo, but a string that does not have a description property.

+4
source

Source: https://habr.com/ru/post/1243072/


All Articles