angularjs tables

Making Custom Report Tables Using AngularJS and Django

We will create a project using Angular CLI, this tool allows you to quickly create corner applications and generate components, services, etc. from the command line. If you start from scratch, generate the project by running the following command:

$ ng new table-app

Then create the table and table components:

$ cd table-app

$ ng g component table

$ ng g component table-row

This will create two components in the src/app directory. The CLI will generate both components and place their files in different directories, src/app/table and src/app/table-row respectively.

src/app

|– table

|– table.component.ts

|– table.component.html

|– table-row

|– table-row.component.ts

|– table-row.component.html

We will have the main component of the application Component Table.

Replace app.component.html with the following code:

<div class=”app-component”>

<h1 class=”text-center”>Adventure Time</h1>

<app-table></app-table>

</div>

Replace table.component.html:

<table>

<tr>

<th>Name</th>

<th>Age</th>

</tr>

<tr>

<td>Finn</td>

<td>10</td>

</tr>

</table>

If you run ng serve and go to localhost: 4200, you will see that your application now displays the main table. To make this a more realistic application, let’s take the columns and data from a service called Adventure Time. Create a file that will contain all our dummy data, called mock-data.ts.

$ cd src/app

$ touch mock-data.ts

Place the dummy data containing information about the nature of Adventure Time in the file. The file should look like this:

export const CHARACTERS: any[] =

[

{

name: ‘Earl of Lemongrab’,

age: ‘Unknown’,

species: ‘Lemon Candy’,

occupation: ‘Earl, Heir to the Candy Kingdom Throne’

},

{

name: ‘Bonnibel Bubblegum’,

age: ’19’,

species: ‘Gum Person’,

occupation: ‘Returned Ruler of the Candy Kingdom’

},

{

name: ‘Phoebe’,

age: ’16’,

species: ‘Flame Person’,

occupation: ‘Ruler of the Fire Kingdom’

},

{

name: ‘Lumpy Space Princess’,

age: ’18’,

species: ‘Lumpy Space Person’,

occupation: ‘Babysitter’

},

]

Now create an Adventure time service that will return column names and dummy data:

$ ng g service adventure-time

Now you should see two new files in the src/app directory. Add two methods to adventure-time.service.ts. One that will return the columns of the table, and one that will return data to the rows of the table. In table.component.ts, import the Adventure Time service and initialize the columns and data in the ngOnInit () method.

Change table.component.html to display a list of columns and a list of characters. Replace the current html with the following text:

<table>

<tr>

<th *ngFor=”let col of columns”>

{{col}}

</th>

</tr>

<tr *ngFor=”let char of characters | async”>

<td *ngFor=”let col of columns”>

{{char[col]}}

</td>

</tr>

</table>

Igor Grigorenko

Add comment