Jake11
Jake11

Reputation: 831

Angular5, issue with referencing dom elements in *ngif

I got a table generated by angular using json, and I want to make row content editable so I added some some *ngif conditions for that so I can switch from read only to edit, but after I done it element hash references isn't working any more as it was when the inputs was outside *ngif.

here's html:

<table class="product-table">
  <thead class="product-table-head">
    <tr class="product-table-head-row">
      <td class="product-cell">id</td>
      <td class="product-cell product-head-cell">name</td>
      <td class="product-cell product-head-cell">price</td>
      <td class="product-cell product-head-cell">actions</td>
    </tr>
  </thead>
  <tbody class="product-table-body">
    <tr *ngFor="let product of products" class="product-table-body-row product-row">
      <td class="product-cell" #prodID>{{product.id}}</td>
      <td class="product-cell">
        <span *ngIf="editRow!==product.id">{{product.name}}</span>
        <span *ngIf="editMode&&editRow===product.id"><input type="text" #nameInputPut class="editInput"></span>
      </td>
      <td class="product-cell">
          <span *ngIf="editRow!==product.id">{{product.price}}$</span>
          <span *ngIf="editMode&&editRow===product.id"><input type="number" #priceInputPut class="editInput">$</span>
      </td>
      <td class="product-cell">
        <i class="fa icon fa-pencil" (click)="editProduct(prodID)" *ngIf="editRow!==product.id"></i>
        <i class="fa icon fa-save" (click)="putProduct(product.id,nameInputPut,priceInputPut)" *ngIf="editMode&&editRow===product.id"></i>
        <i class="fa icon fa-trash"></i>
      </td>
    </tr>
  </tbody>
</table>

here's function that handle that:

putProduct(productId,productName,productPrice){

let prodName = productName.value,
    prodPrice = productPrice.value;

 .....
}

and I get error message in console's says: "productName is undefined" although I access productId which isn't inside *ngif.

What is the way to get around that ?

Upvotes: 0

Views: 53

Answers (1)

Himanshu Arora
Himanshu Arora

Reputation: 2568

Why do we need refrence #nameInputPut. I guess you should use input fields with ngModel like:

<input type="text" id="name" [(ngModel)]="product.name" name="name">

Also, initialize product to an empty JSON {} at the time of declaration or in the constructor. So that the expressions product.<something> don't fail due to product being undefined initially.

Upvotes: 1

Related Questions