6

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.

2
  • 5
    Shouldn't that be let row of (table | async).content? Commented Jan 9, 2017 at 9:04
  • 1
    @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 Commented Jan 9, 2017 at 9:08

3 Answers 3

14

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Yes thats great, thank you and @jonrsharpe but I have to add an ? otherwise 'content' is null before the first next()
1

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>

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.