Angular 7 Example

I start this tutorial by installing Angular using Angular CLI

I assume you have installed an Angular CLI

If it’s not in your machine, run the following command.

npm install -g @angular/cli

And then create a boilerplate project by running the following command.

ng new testAngular

go into the project folder

cd testAngular

open the project in your editor. I’m using Visual Studio Code.

code .

Start the project by running the following command.

ng serve --open

Install Bootstrap in your app. Go to your root. Run the following code.

npm add bootstrap

Copy the bootstrap.min.css file from \node_modules\bootstrap\dist\css to \src\assets\css folder.

If the CSS is not there, then create a folder named “css”.

Add the link of that CSS file inside src > index.html as you can see.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TestAngular</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <app-root></app-root>
</body>
</html>

Create two components named “home” and “employees” by running the following command

ng g c home
ng g c employees

Angular automatically update the app.module.ts file.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { EmployeesComponent } from './employees/employees.component';

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

Modify the app-routing.module.ts file as follows

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { EmployeesComponent } from './employees/employees.component';
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'employees', component: EmployeesComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

As you can see, I have the Routes, RouterModule module. I have populated the routes array.

Exporting RouterModule provides router directives.

<router-outlet></router-outlet>

router-outlet is a component that is used to load the different components dynamically based on the activated component. It is inside the app.component.html file.

I define a navbar to display the output of the different routes. Inside the app.component.html file, add the following code.

<div id="app">
  <nav class="navbar navbar-expand-sm bg-light">
      <ul class="navbar-nav">
      <li class="nav-item">
          <a routerLink="/home" class="nav-link">Home</a>
      </li>
      <li class="nav-item">
          <a routerLink="/employees" class="nav-link">Employees</a>
      </li>
      </ul>
  </nav>
  <div class="container">
      <router-outlet></router-outlet>
  </div>
</div>

I will prepare the fake data using a package called json-server. Run the following commandto install the json-server package.

npm install -g json-server

I will create a folder named “data” inside the src directory and create a file named db.json inside that.

{
    "results": [
    {
        "id": "1",
        "name": "Cihan",
        "company": "ABC"
    },
    {
        "id": "2",
        "name": "John",
        "company": "DEF"
    },
    {
        "id": "3",
        "name": "Robert",
        "company": "XYZ"
    }]
}

That’s OK. Start the JSON Server by running the following command.

json-server --watch src/data/db.json --port 3000

http://localhost:3000/results

Angular has HttpClientModule module. Let us configure inside the app.module.ts file.

import { HttpClientModule } from '@angular/common/http';
imports: [
  BrowserModule,
  AppRoutingModule,
  HttpClientModule
]

Create a file named Employee.ts inside the employees folder. Type the following code in that.

export interface Employee {
  id: Number;
  name: String;
  company: String;
}

Create a file named employee.service.ts inside the employees folder. In that file, I’m writing the network request code.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class EmployeeService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:3000';
  getEmployees() {
    return this
            .http
            .get(`${this.url}/results`);
        }
}

Then I import this file inside the employees.component.ts file. Then I call the service as follows.

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';
import { Employee } from './employee';

@Component({
  selector: 'app-employees',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {

  employees: Employee[];
  constructor(private employeeService: EmployeeService) { }

  ngOnInit() {
    this.employeeService.getEmployees().subscribe((data: Employee[])=>{
      this.employees = data;
    });
  }

}

Display that data inside the employees.component.html file.

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Company</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let employee of employees">
      <td>{{ employee.id }}</td>
      <td>{{ employee.name }}</td>
      <td>{{ employee.company }}</td>
    </tr>
  </tbody>
</table>

Finally I will declare the EmployeeService service as a provider inside the app.module.ts file.

import { EmployeeService } from './employees/employee.service';
providers: [EmployeeService]

Leave a Reply

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