我试图从表中删除一行。但是当我把删除按钮放在一行的末尾时,我收到了一个错误TypeError: Cannot read property 'value' of undefined
。我遵循了这个video link,但我只需要在没有加载行数据的情况下使删除按钮正常工作。
//service.ts
deleteProduct(key: string) {
this.productList.remove(key);
}
//component.ts
onDelete(form: NgForm) {
//fungsi deleteProduct()
if (confirm('Are you sure to delete this record ?') == true) {
this.ProductService.deleteProduct(form.value.$prdKey);
//this.resetForm(form);
}
}
onItemClick(prd: Product) {
this.ProductService.selectedProduct = Object.assign({}, prd);
}

<!--the form-->
<form #productForm="ngForm" (ngSubmit)="onSubmit(productForm)">...</form>
<tr *ngFor="let product of productList">
<td>{{product.prdName}}</td>
<td><button type="button" class="btn btn-warning" (click)="onItemClick(product)" title="click to edit or delete" data-toggle="modal" data-target="#myModal">Update</button></td>
<td><button type="button" class="btn btn-danger" *ngIf="ProductService.selectedProduct.$prdKey == null" (click)="onDelete(ProductService.selectedProduct.$prdKey)">Delete</button></td>
</tr>
&#13;
视频教程版本实际上是*ngIf="ProductService.selectedProduct.$prdKey != null"
。我创建了*ngIf="ProductService.selectedProduct.$prdKey == null"
,因此删除按钮将显示在行的末尾,而不会先单击一行。谁能帮我解决这个问题?如果需要更多代码段,请告诉我。先感谢您。
答案 0 :(得分:1)
这是因为onDelete()
您传递的是string
类型的密钥,但在onDelete()
定义中您希望它为 NgForm 类型。
Chnage onDelete(form: NgForm) {
至onDelete(key: string) {
试试这个
onDelete(key: string) {
//fungsi deleteProduct()
if (confirm('Are you sure to delete this record ?') == true) {
this.ProductService.deleteProduct(key);
//this.resetForm(form);
}
}
答案 1 :(得分:1)
失去了一些问题:
<button type="button" class="btn btn-danger"
*ngIf="ProductService.selectedProduct.$prdKey == null"
(click)="onDelete(ProductService.selectedProduct.$prdKey)">
Delete
</button>
ProductService.selectedProduct.$prdKey == null
表示当$prdKey
为空时显示删除,
所以onDelete(ProductService.selectedProduct.$prdKey)
这将始终将null传递给onDelete
onDelete(form: NgForm)
,您已将参数设置为NgForm
,但如上所述,您将获得null
form.value.$prdKey
此行会抛出错误TypeError: Cannot read property 'value' of undefined
您应该使用:*ngIf="ProductService.selectedProduct.$prdKey != null"
因为它是完美的逻辑,并使用$prdKey null
删除所有产品。
答案 2 :(得分:1)
试试这个
//component.ts
onDelete(key: string) {
//fungsi deleteProduct()
if (confirm('Are you sure to delete this record ?') == true) {
this.ProductService.deleteProduct(key);
this.productList.remove(key);
//this.resetForm(form);
}
}