6
votes

I have a Angular2 Component displaying some data in a table.

export class DiagnosisComponent {

  headers: Array<String> = ["hello world", "hello world"];
  table: Observable<TableData>;

  constructor(private eventService: EventService) {
    this.table = this.eventService.getDiagnosisEvents();
    this.table.subscribe(console.log.bind(console));
  }

}

And here is the TableData class

export class TableData {

  content: Array<any>;
  paging: Paging;

  constructor(obj: any) {

    this.paging = {
      size: obj.size,
      totalElements: obj.totalElements,
      currentPage: 1
    };

    this.content = obj.content;

  }

}

export interface Paging {
  size: number;
  totalElements: number;
  currentPage: number;
}

Now I want to bind the table.content Array to a *ngFor with a async pipe. My problem is that i need to get the nested data, and not the TableData itself.

<div class="row">

  <vpscout-filter></vpscout-filter>

  <table class="table">
    <thead>
    <tr><th *ngFor="let header of headers">{{header | translate}}</th></tr>
    </thead>
    <tbody>
    <tr *ngFor="let row of table | async ">
      <td>test</td>
    </tr>
    </tbody>
  </table>

</div>

Changing the *ngFor to <tr *ngFor="let row of table.content | async "> does not work.

3
Shouldn't that be let row of (table | async).content? - jonrsharpe
@jonrsharpe you should really provide these as an answer (I can understand that you don't need points anymore but still.. :P). It's definitely a solution stackoverflow.com/a/35302622/5706293 - eko

3 Answers

13
votes

I solved a similar problem like this:

<tr *ngFor="let row of (table | async)?.content ">
      <td>test</td>
</tr>

Since, I'm using immutableJs for my project and converting the observable data to map, the exact solution that worked for me was:

<tr *ngFor="let row of (table | async)?.get('content') ">
      <td>test</td>
</tr>
1
votes

You can create a new field for the content:

this.table.subscribe((data)=>{
   this.tableContent = data.content
});

and bind that new field to the *ngFor

 <tbody *ngIf="tableContent">
    <tr *ngFor="let row of tableContent">
      <td>test</td>
    </tr>
 </tbody>
-1
votes

table is of type Observable and not an instance of the TableData class. You need to use the Observable's subscribe method to assign an instance of TableData to a variable that is bound to the template/view.