Search code examples
angularangular2-routingangular2-templateangular2-services

Binding a dynamic object to Html using Angular2


this.procFilterResults: any[];    
this.procservices.GetProcData(this.selectedServer, this.selectedProjectName,
                              this.selectedProc, this.procInput,_inputs ) 
  .subscribe(res => {                
            this.procFilterResults = JSON.parse(res);
            this.Keys=Object.keys(this.procFilterResults[0]);                
            console.log(this.procFilterResults);
         },
        error => this.errorMessage = <any>error);

 <table class="table table-bordered">
        <thead>
          <th *ngFor="let key of Keys">
             {{key}}
          </th>
        </thead>
    <tbody>
      <tr *ngFor= 'let res of procFilterResults'>

      </tr>
    </tbody>
 </table> 

Based on my inputs I am getting the new object for every request. And I want to bind the result to the table. Is there any way that with out deserializing the object can I bind to HTML table.?


Solution

  • You could create a consider reformat dynamic object in two dimensional format. I haven't tested below code please give a try once.

    // Add this inside subscribe
    this.Keys = (this.procFilterResults.length || []) && 
                 Object.keys(this.procFilterResults[0]);
    this.results = this.procFilterResults.map(
      element => {
       let obj = [];
       this.Keys.forEach(key => obj.push({key: key, value: element[key]}))
       return obj;
      }
    )
    

    Html

    <table class="table table-bordered">
        <thead>
           <th *ngFor="let key of Keys">
              {{key}}
           </th>
        </thead>
        <tbody>
          <tr *ngFor='let res of results'>
             <td *ngFor="let item of res">
                {{item.value}}
             </td>
          </tr>
        </tbody>
    </table> 
    

    I had intentionally had a key inside result array, so that in future you can easily perform searching, filtering, sorting kind of functionality easily.