Search code examples
angularangular-datatables

Display value for specific table row only in *ngFor


I am trying to display a value for a specific table row however the value is getting displayed for every single row. I am using angular-data-tables.

Here is my code

<tr *ngFor="let item of mf.data; let i=index" (click)="getCustomerAccounts(item)">
    <td>{{i+1}}</td>
    <td>{{item.href}} 
      <tr>
        <div class="card" *ngIf="msgFound">
          <div class="card-body">
            {{msgFound}}
          </div>
        </div>
      </tr>
    </td> 
</tr>

So the msgFound value is getting repeated in every row. Here is a screen shot of the problem enter image description here

The code which generates msgFound looks like this. It basically allows the user to click on a row and if the row value matches a value in a JSON file then msgFound or msgNotFound is assigned a value.

  getBillingCycles() {
    this.BillingCyclesService.getBillingCycles()
    .subscribe((data: any) => {
      this.billingLink = data;
      this.billing = data._links.self;
    });
  }

  getCustomerAccounts(selectedItem: any) {
    this.CustomerAccountsService.getCustomerAccounts()
    .subscribe((data: any) => {
      this.customerAccounts = data;
      this.customerAccounts._embedded.accountList.forEach(longLink => {
          if (longLink.link.href.indexOf(selectedItem.href) != -1) {
            this.msgFound = longLink.accountNumber;
          } else {
            this.msgNotFound = 'No match for ' + selectedItem.href
          }
      });
    });
  }

Solution

  • What you want to do here is set your index. The easiest way to do this would require to give the index from the html to your component:

    (click)="getCustomerAccounts(item, i)"

    And in your component something like:

    getCustomerAccounts(selectedItem: any, index: number) {
      //http call and after
      if (longLink.link.href.indexOf(selectedItem.href) != -1) {
         this.msgFound = { value: longLink.accountNumber, index: index};
      } else {
         this.msgFound = { value: 'No match for ' + selectedItem.href, index: index};
      }
    

    Now you need a little change in your html:

    <div class="card-body" *ngIf="msgFound !== undefined && i === msgFound.index">
      {{msgFound.value}}
    </div>