我正在尝试将值推入数组,然后在视图中显示。一切正常,但我想在项目中添加自动增量编号。我在data.json
文件中有以下数组
[
{"id":1,"name":"John","gender":"Male"},
{"id":2,"name":"Smith","gender":"Male"},
{"id":3,"name":"Linda","gender":"Female"},
{"id":4,"name":"Jerry","gender":"Female"}
]
在user.service
档案
private JsonDirectory: string = "assets/data.json"
constructor(private _httpReference: Http){}
getUsers(){
return this._httpReference.get(this.JsonDirectory)
.map((responseReference:Response) => responseReference.json());
}
在user.component
中我将输入值推送到pressEnter事件的数组中,因为我只有一个输入值所以我已经推送但是还有id
并且它应该自动递增。以下是我正在尝试的代码
UserArray = [];
constructor(private userService: UserService, private _location: Location){}
show_value: string = '';
OnPressEnter(show_value: string){
var inputValue = show_value;
this.show_value = show_value;
this.UserArray.push({"id":5,"name":inputValue });
}
你可以看到id是静态的我想让它变得动态。
<ul>
<li *ngFor="let userCourse of UserArray" (click)="onSelect(userCourse.name)">
<span>{{userCourse.id}}</span> | <a style="cursor:pointer;">{{userCourse.name}} </a>
</li>
</ul>
答案 0 :(得分:2)
你可以像这样使用
OnPressEnter(show_value: string){
var inputValue = show_value;
this.show_value = show_value;
this.UserArray.push({"id":this.UserArray.length+1,"name":inputValue });
}