Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngFor - Loop two arrays in the same level

I'm trying to loop two arrays by using one *ngFor but it doesn't show any element on the browser. I have sample of HTML file below also initialized arrays in component file.

HTML file:

<tbody *ngIf="feedbacks.length">
          <ng-container *ngFor="let fd of feedbacks;let res of results;let i=index">
            <tr>
              <td>{{ i }}</td>
              <td>{{fd}}</td>
              <td colspan="2">
                <ul>
                  <div *ngFor="let obj of res">
                    <td>Score: {{res.score}}</td>
                    <td>Emotion: {{res.tone_name}}</td>
                  </div>
                </ul>
              </td>
            </tr>
          </ng-container>
        </tbody>

Typescript file :

  results = [];
  feedbacks = [];

  ngOnInit(){

    this.feedbacks = ["Le système est trop lent ", "Le top! Un exemple d'excellence.", "C'est quoi ce bordel !"]; 

    this.results = [
      [{score: 0.535632, tone_id: "anger", tone_name: "Colère"}],
      [{score: 0.633569, tone_id: "anger", tone_name: "Colère"},
       {score: 0.506763, tone_id: "analytical", tone_name: "Analytique"}],
      [{score: 0.895438, tone_id: "joy", tone_name: "Joie"}]  
    ];
    console.log(this.results);

  }
like image 336
Atom Avatar asked Sep 21 '18 10:09

Atom


2 Answers

use let obj of results[i] for this.

<tbody *ngIf="feedbacks.length">
    <ng-container *ngFor="let fd of feedbacks;let i=index">
        <tr>
            <td>{{ i }}</td>
            <td>{{fd}}</td>
            <td colspan="2">
                <ul>
                    <div *ngFor="let obj of results[i]">
                        <td>Test: {{obj.score}}</td>
                    </div>
                </ul>
            </td>
        </tr>
    </ng-container>
</tbody>
like image 128
Krishna Rathore Avatar answered Oct 01 '22 16:10

Krishna Rathore


The ngFor structural directive only accepts a single iterable as input. It won't accept more than one array. Instead of trying to loop through two separate arrays, I would suggest creating a single array (provided both arrays are of the same length).

// HTML

<tbody *ngIf="feedbacks.length">
   <ng-container *ngFor="let item of combinedArray;let i=index">
     <tr>
       <td>{{ i }}</td>
       <td>{{fd}}</td>
         <td colspan="2">
           <ul>
             <div *ngFor="let obj of item.result">
               <td>Test: {{obj.score}}</td>
             </div>
           </ul>
       </td>
    </tr>
  </ng-container>
</tbody>

// Typescript

combinedArray: { feedback: any, results: any }[] = [];

ngOnInit(){
  ...

  this.feedbacks.forEach((fb, index)
    => this.combinedArray.push({ feedback: fb, result: this.results[index] }));
}
like image 43
Wingnod Avatar answered Oct 01 '22 14:10

Wingnod