Angular2-添加新的< li>项目onClick事件 [英] Angular2 - Adding new <li> item onClick event
问题描述
我使用* ng迭代数组以便在列表中显示它们,但是我无法在列表中添加新项目.在Onclick事件中,我得到了一个空的li.可能我没有链接正确的东西?指令?要不然是啥?也许我使用了错误的变量?
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) { }
}
我将上述类加载到我的app.component.ts中,代码如下.我在我的主要html所在的位置使用templateUrl(您可以在第3个代码部分看到它).
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);
}
}
}
我的主要app.component html是:
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>
推荐答案
这是解决您的问题的演示:
here is working demo for your problem:
只需更改您的方法,如下所示:
Just changed your method like this:
addInfo(newInfo:string) {
if (newInfo) {
this.information.push(new ContactInfo(newInfo));
}
}
您尚未为exported
类ContactInfo
创建新实例,因此,您的字符串未正确推入数组.
you have not created a new instance for the exported
class ContactInfo
because of this your string is not properly pushing in the array.
这篇关于Angular2-添加新的< li>项目onClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!