ngFor - Unable to sort array of objects Angular 5

427 Views Asked by At

I have array of array of objects in Angular and I'm trying to sort into HTML.

The output of array is show in chrome console :

enter image description here

With sample inside the array :

enter image description here

in typescript file:

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"}],
  [{score: 0.736445, tone_id: "joy", tone_name: "Joie"},
   {score: 0.955445, tone_id: "analytical", tone_name: "Analytique"}],
  [{score: 0.796404, tone_id: "anger", tone_name: "Colère"}],
  [{score: 0.52567, tone_id: "sadness", tone_name: "Tristesse"},
   {score: 0.639934, tone_id: "anger", tone_name: "Colère"}],
  [{score: 0.557769, tone_id: "fear", tone_name: "Peur"}],
  [{score: 0.51583, tone_id: "joy", tone_name: "Joie"},
  {score: 0.874372, tone_id: "confident", tone_name: "Confiant"}]    
];

In the html file, I'm looping the array initialized as results using *ngFor but can't display objects inside array:

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

It shows empty result in table on the browser.

1

There are 1 best solutions below

1
On

With *ngFor="let res of results", res is going to be whatever is at each index in results. In each case it's going to be another array, so you'll need another *ngFor to go through its contents.

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