PrimeNG Tutorial - DataTable Dynamic Columns Example

PrimeNG Tutorial - DataTable Dynamic Columns Example


Overview

In previous tutorial we had implemented PrimeNG Tutorial - Datatable Hello World Example . We will be modifying the source code we had developed in previous tutorial for the Datatable. In that example we had implemented the basic datatable we will now be making changes for dynamic columns. Suppose we have a scenario where we are not sure of the number of columns our datatable will be having. In such scenario we will need to modify the code we had developed in previously.

Table Of Contents :


Video Tutorial

Implementation

  • In previous tutorial we had implemented PrimeNG Datatable component. If we run the application and go to localhost:4200/books we get the following book list-
    PrimeNG DataTable
  • Create a backing object named cols. It will be an array of name-value pairs for the columnn header names.
    import { Component, OnInit } from '@angular/core';
    import { BookService, Book } from '../service/book.service';
    
    @Component({
      selector: 'app-book-data',
      templateUrl: './book-data.component.html',
      styleUrls: ['./book-data.component.css']
    })
    export class BookDataComponent implements OnInit {
    
      books: Book[];
    
      cols: any[];
    
      constructor(private bookService: BookService) { }
    
      ngOnInit() {
          this.bookService.getBooks().
          then(books => this.books = books);
    
         this.cols = [
            { field: 'name', header: 'Name' },
            {field: 'author', header: 'Author' },
            { field: 'price', header: 'Price' }      
        ];
      }
    
    }
    
  • Next we will be making use of the angular ng for directive to iterate the cols field to get the column headers as well as the row data.
    <p-table [columns]="cols" [value]="books">
      <ng-template pTemplate="header" let-columns>
          <tr>
            <th *ngFor="let col of columns">
                {{col.header}}
            </th>         
          </tr>
      </ng-template>
      <ng-template pTemplate="body" let-rowData let-columns="columns">
        <tr>
            <td *ngFor="let col of columns">
                    {{rowData[col.field]}}
            </td>
        </tr>
      </ng-template>
    </p-table>
    
  • If we now go to - localhost:4200/books we see the following-
    PrimeNG DataTable

Downloads-

PrimeNG DataTable Dynamic Columns Example