使用angular推送数组中的项目时如何添加自动递增编号?

Aya*_*hah 1 angular

我试图将值推入数组,然后在视图中显示。一切工作正常,但我想添加自动递增编号。我在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"}
]
Run Code Online (Sandbox Code Playgroud)

user.service文件中

private JsonDirectory: string = "assets/data.json"
constructor(private _httpReference: Http){}
getUsers(){
    return this._httpReference.get(this.JsonDirectory)
        .map((responseReference:Response) => responseReference.json());
}
Run Code Online (Sandbox Code Playgroud)

user.componenti中,我在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 }); 
    }
Run Code Online (Sandbox Code Playgroud)

您可以看到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>
Run Code Online (Sandbox Code Playgroud)

小智 5

你可以这样使用

  OnPressEnter(show_value: string){ 
            var inputValue = show_value;
            this.show_value = show_value;
            this.UserArray.push({"id":this.UserArray.length+1,"name":inputValue }); 
        }
Run Code Online (Sandbox Code Playgroud)