Home > Back-end >  Is there a way to pass `ngFor` item as a parameter to a function
Is there a way to pass `ngFor` item as a parameter to a function

Time:09-28

I am getting shuffled object value from backend. to fix that, I want to retrive the exact value by title. but how to pass from different ngFor loop in to others/

html:

<ng-container *ngIf="hfsTableSchema">
  <table>
    <thead>
      <tr>
        <th *ngFor="let header of headers; let i = index"  >{{header.title}}</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let object of rows">
        <td *ngFor="let item of object|keyvalue">{{setValue(object, header)}}</td>//how?
      </tr>
    </tbody>
  </table>
</ng-container>

because I could not able to use the item.value directly. the values are not correct as per header label.

I want to do this;

setValue(object, header){
  return object[header.tite]
}

so it will match the correct value. any one help me please?

CodePudding user response:

If your header is some like

header=[{title:'One',column:'one'},{title:'Two',column:'two'},..]

iterate again over headers for the td

<tr *ngFor="let object of rows">
    <td *ngFor="let header of headers">{{object[header.column]}}</td>
</tr>

CodePudding user response:

You can't access a value of the *ngFor outside of its template. It has to be a child to access the value.

This is intentional because we want the value to be scoped and not leaked into other part of the HTML.

That's why we can do this following without any errors:


<div *ngFor="let item of products">{{item}}</div>

<div *ngFor="let item of employers">{{item}}</div>

<!-- item value is scoped, so it won't interfere with one another-->

What you can do is to use the headers in the td loop:

<ng-container *ngIf="hfsTableSchema">
  <table>
    <thead>
      <tr>
        <th *ngFor="let header of headers; let i = index">{{header.title}}</th>
      </tr>
    </thead>

    <tbody>
      <tr *ngFor="let object of rows">
        <td *ngFor="let header of headers">{{object[header.title]}}</td>
      </tr>
    </tbody>
  </table>
</ng-container>
  • Related