我正在尝试建立一个ec-ommerce网站,所以我面临的问题是,在表单中输入我的值时,然后单击“保存”按钮,我的值被添加到一个空数组中,该数组在我的声明中服务,但我还想在将每个产品添加到服务中的数组时自动向其添加id。我该怎么做?
html文件
<div class="col-md-5">
<form (ngSubmit)="onsubmit()" #f="ngForm">
<div class="md-form form-group mt-5">
<input mdbInput type="text" class="form-control"
id="formGroupExampleInputMD" placeholder="Title"
ngModel name="title" required #title="ngModel"
>
</div>
<div class="md-form form-group mt-5">
<input mdbInput type="text" class="form-control"
id="formGroupExampleInput2MD" placeholder="Price"
ngModel name="price" required #price="ngModel">
</div>
<div class="md-form form-group mt-5">
<select class="browser-default custom-select"
ngModel name="select" required #select="ngModel">
<option value=""></option>
<option *ngFor="let c of category|async" [value]="c.$key"> .
{{c.name}}</option>
</select>
<div class="md-form form-group mt-5">
<input mdbInput type="text" class="form-control"
id="formGroupExampleInput2MD" placeholder="imageurl"
ngModel name="imageurl" required #imageurl="ngModel"
>
</div>
</div>
<button type="submit" mdbBtn color="primary"
mdbWavesEffect>Save</button>
</form>
</div>
component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { CategoryserviceService } from
'src/app/sevices/categoryservice.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-newproducts',
templateUrl: './newproducts.component.html',
styleUrls: ['./newproducts.component.scss']
})
export class NewproductsComponent implements OnInit {
@ViewChild('f') form:NgForm
category
constructor(private ctservice:CategoryserviceService) {
}
ngOnInit() {
}
onsubmit(){
// console.log(this.form.value)
this.ctservice.addtocards(this.form.value)
}
}
服务文件
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CategoryserviceService {
cards:any[]=[]
constructor() {
}
addtocards(values){
this.cards.push(values)
console.log(this.cards)
}
}
答案 0 :(得分:3)
如果要为每个项目添加一些唯一ID,则可以利用 cards 数组的长度。
addtocards(values){
values['id'] = this.cards.length;
this.cards.push(values)
console.log(this.cards)
}
因此,最初的长度为0。因此,它成为第一个产品的ID。
对于 n 个产品,其ID为 n-1