Display Data On HTML Table From Server Using Angular And Alternate Row Color

Introduction

In this tutorial I am going to show you how to display data from server using Angular 9 and how to apply two different colors on alternate rows using css (cascading style sheet). I will use Spring Boot REST API to send data on client side and consume using client side technology Angular 9.

I will use ngIf, else, ngFor directives to render data conditionally. I will show elseBlock if no record is found from the REST API. I will use index to determine odd or even column and accordingly apply color to the rows.

Prerequisites

Angular 9/13, Node 16.12.0, Npm 8.1.0, CSS, HTML, REST API Endpoint – /products

Project Setup

How to Create Angular Project

Execute the command ng new angular-html-table-alternate-row-color in CLI tool to create a new angular project.

Model Class

I will map JSON object from the server into client side object. The class file product.ts is created under src/app folder.

Therefore I am creating a class called Product which has below attributes:

export class Product {
  id?: number;
  name: string;
  code: string;
  price: number;
}

The class is straight forward and notice ?, which indicates optional value for id field. Generally ? is not required when you are fetching data from server but may be required when you want to save data if you are generating id value on server side.

For Angular 13:

I am using interface instead of class for model.

export interface Product {
  id?: number;
  name: string;
  code: string;
  price: number;
}

Service Class

Service class is required to process your business logic. The class file product.service.ts is created under src/app folder.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Product } from './product';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({ providedIn: 'root' })
export class ProductService {
  private productUrl = 'http://localhost:8080';  // URL to REST API
  
  constructor(private http: HttpClient) { }
  
  /** GET products from the server */
  getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(this.productUrl + '/products');
  }
  
}

Notice I have used @Injectable({ providedIn: 'root' }) to make the service class singleton.

A singleton service is a service for which only one instance exists in an app.

There are two ways to make a service a singleton in Angular:

  • Set the providedIn property of the @Injectable() to “root”.
  • Include the service in the AppModule or in a module that is only imported by the AppModule (explained later).

Change Page Title Globally

I will replace the title in the file src/index.html with the below title:

<title>Display Data from Server using Angular on HTML Table and Alternate Row Color</title>

If you want to change title for specific title then you have set in the corresponding *.component.ts file.

Load Required Module Globally

I need to import required module such as HttpClientModule into the file src/app/app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule }    from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
	HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I discussed about making service class singleton and I could have included the ProductService class into the above file inside provides: [], such as, providers: [ProductService].

Load Data into Component

In order to display data on HTML file I need to load data into corresponding component TypeScript file. So here I have only app component, so I am going to use app.component.ts file under src/app directory.

import { Component, OnInit } from '@angular/core';

import { Product } from './product';
import { ProductService } from './product.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
	products: Product[] = [];
	
	constructor(private productService: ProductService) { }
	
	ngOnInit() {
		this.getProducts();
	}
	
	getProducts(): void {
		this.productService.getProducts().subscribe(products => this.products = products);
	}
}

Display Data on HTML Table

Now I will display data on HTML table.

<h1>Display Data on HTML Table from Server using Angular and Alternate Row Color</h1>

<div *ngIf="products; else elseBlock">
	<table class="datatable">
		<thead>
			<tr>
				<th>ID</th>
				<th>Code</th>
				<th>Name</th>
				<th>Price</th>
			</tr>
		</thead>
		<tbody>
			<tr *ngFor="let p of products">
				<td>{{ p.id }}</td>
				<td>{{ p.name }}</td>
				<td>{{ p.code }}</td>
				<td>{{ p.price }}</td>
			</tr>
		</tbody>
	</table>
</div>
<ng-template #elseBlock>No record found</ng-template>

Testing the Application

Now when you run your application by executing command ng serve --open, which opens automatically on system default browser at http://localhost:4200 URL.

The product data on HTML table looks similar to the below image:

display data on html table from server using angular and alternate row color

Apply CSS Style

I will apply some basic style on HTML table to look better. I will also apply two different colors on alternate rows or odd/even rows on HTML table.

Just copy and paste below CSS rules into src/app/app.component.css file.

table.datatable {
	width:100%;
	border: none;
	background:#fff;
}
table.datatable td.table_foot {
	border: none;
	background: #fff;
	text-align: center;
}
table.datatable tr.odd_col {
	background: none;
}
table.datatable tr.even_col {
	background: #ddd;
}
table.datatable td {
	font-size:10pt;
	padding:5px 10px;
	text-align: left;
}
table.datatable th {
	text-align: left;
	font-size: 8pt;
	padding: 10px 10px 7px;   
	text-transform: uppercase;
	color: #fff;
	background-color: black;
	font-family: sans-serif;
}

Apply Odd/Even Rule on Table Rows

Next I need to apply odd/even rules on HTML table. I will determine using the following code snippets on <tr/>.

[ngClass]="odd ? 'odd_col' : 'even_col'"

The complete <tr/> looks as below:

<tr *ngFor="let p of products; let odd = odd" [ngClass]="odd ? 'odd_col' : 'even_col'">

Testing the Application

Now your page looks similar to the below image:

display data on html table from server using angular and alternate row color

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *