Angular,TypeError:无法读取属性' value'未定义的

时间:2017-11-20 04:55:14

标签: angular typescript html-table

我试图从表中删除一行。但是当我把删除按钮放在一行的末尾时,我收到了一个错误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;
&#13;
&#13;

视频教程版本实际上是*ngIf="ProductService.selectedProduct.$prdKey != null"。我创建了*ngIf="ProductService.selectedProduct.$prdKey == null",因此删除按钮将显示在行的末尾,而不会先单击一行。谁能帮我解决这个问题?如果需要更多代码段,请告诉我。先感谢您。

3 个答案:

答案 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>
  1. ProductService.selectedProduct.$prdKey == null表示当$prdKey为空时显示删除, 所以onDelete(ProductService.selectedProduct.$prdKey)这将始终将null传递给onDelete

  2. onDelete(form: NgForm),您已将参数设置为NgForm,但如上所述,您将获得null

  3. form.value.$prdKey此行会抛出错误TypeError: Cannot read property 'value' of undefined

  4. 您应该使用:*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);
  }
}