• Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
test
Code4Developers

Code4Developers

Code4Developers
  • Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
  • Angular

Angular 6 CRUD – Part 1: Project Setup, Routing, Service

  • Nisarg Dave
  • May 9, 2018
  • 5 minute read
Angular
Total
0
Shares
0
0
0

This article is Part 1 Angular 6 CRUD. In this article and upcoming article, we will discuss performing CRUD operations in Angular 6 i.e. Creating, Reading, Updating and Deleting in Angular 6 with simple examples. We will also discuss about the Angular 6 Project setup, apply Routing, create service to read and display data, create forms for create, update and delete data. Let us start this tutorial by installing Angular 6 using Angular CLI and then working on our tutorial.

We will follow below mentioned steps.

  1. Set up the Angular 6 Development Environment
  2. Install Bootstrap 4 in an Angular 6 application
  3. Configure Routing and Navigation for components
  4. Create a JSON server that serves the data.
  5. Setup HttpClient for service.

Step 1: Set up the Angular 6 Development Environment

You need to set up your development environment before you can do anything.

Install Node JS and NPM (Node Package Manager) if they are not already on your machine.

For developing Angular 6 application, verify that you are running at least Node.js version 8.x or greater and npm version 5.x or greater by running node -v and npm -v in a terminal/console window.

Then install the Angular CLI globally.

npm install -g @angular/cli

Create new project by running the following command:

ng new employee-app

you can also download sample application from https://angular.io/generated/zips/cli-quickstart/cli-quickstart.zip

Go to the project directory and launch the server.

cd employee-app
ng serve –open

The ng serve command launches the server, watches your files, and rebuilds the app as you make changes to those files.

Using the –open (or just -o) option will automatically open your browser on http://localhost:4200/.

Step 2: Install Bootstrap 4 in an Angular 6 application.

We will be using Bootstrap for styles in our application. So, install Bootstrap by executing the following command from the command prompt.

npm install bootstrap@4 –save

Once Bootstrap is installed, open angular.json file and specify the path to the Bootstrap style-sheet (bootstrap.min.css) in the styles property as shown below.

// angular.json

"styles": [
               "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              {
                "input": "src/styles.css"
              }
            ],

Step 3: Configure Routing and navigation for components.

Now, create a component to display the list of employees. Name it ListEmployeesComponent.

Creating ListEmployeesComponent : Use the following AngularCLI command to create ListEmployeesComponent. We will place all employee CRUD components in “employees” folder. This is the reason we prefixed the “employees” folder name in the command. Also, notice we have set –flat option to true as we do not want to place the ListEmployeesComponent files in it’s own dedicated folder.

ng g c employees/listEmployees --spec false --flat true

The above command not only creates the ListEmployeesComponent, it also updates the AppModule. In the app.module.ts file it has imported ListEmployeesComponent and included it in the declarations array.

Now, create another component.

ng g c employees/createEmployee --spec false --flat true

Now, Angular is Framework and not just library. So, it has Router and Http module already included.
So, first, we will integrate routing for our application.

To configure routes, we first need to import Routes type from ‘@angular/router’

Now we have to write whole code inside app.module.ts file.

// app.module.ts 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ListEmployeesComponent } from './employees/list-employees.component';
import { CreateEmployeeComponent } from './employees/create-employee.component';
 // Import RouterModule
import { RouterModule,Routes } from '@angular/router';

// Each route maps a URL path to a component
// The 3rd route specifies the route to redirect to if the path
// is empty. In our case we are redirecting to /list

// pathMatch property value can be full or prefix. For now we 
// will set it to full as we want to do a full match
 const appRoutes: Routes = [
  { path: 'list', component: ListEmployeesComponent },
  { path: 'create', component: CreateEmployeeComponent },
  { path: '', redirectTo: '/list', pathMatch: 'full' }
];

// To let the router know about the routes configured above,
// pass "appRoutes" constant to forRoot(appRoutes) method
@NgModule({
  declarations: [
    AppComponent,
    ListEmployeesComponent,
    CreateEmployeeComponent
  ],
  imports: [
    BrowserModule,HttpClientModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [EmployeeService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now we need to display the output of the different routes. So, we need to define a <router-outlet> component. Also, we need to create a navigation menu, so that we can easily navigate to different routes and associated components. So, inside app.component.html file, add the following code. It is root component of our Angular 6 application.

// app.component.html 
<div class="container">
    <nav class="navbar navbar-default">
        <ul class="nav navbar-nav">
            <li> <a routerlink="list">Employee List</a> </li>
            <li> <a routerlink="create">Add Employee</a> </li>
        </ul>
    </nav>
    <router-outlet></router-outlet>
</div>

As you can see, in the HTML we have 2 things – Navigation menu and the <router-outlet> directive. The navigation menu is always displayed. Below the navigation menu, we have the <router-outlet> directive. This is the location where the routed component view template is displayed.

Save the file and open the browser and go to http://localhost:4200/

You can see that we have now routing functionality.

Step 4: Create a JSON server that serves the data.

We need the fake data to work with that is why we have to use one package called json-server for this demo. With it, we can make a fake REST api.

Install json-server package using NPM (node package manager).

npm install -g json-server

create one file called Employee.json . Let us add the following data inside Employee.json file.

// Employee.json 

{
    "employees": [{
        "id": 1,
        "name": "ND",
        "city": "Mumbai",
    "gender":"Male",
    "department":"Web"
    }, {
        "id": 2,
        "name": "Joy",
        "city": "Delhi",
    "gender":"Male",
    "department":"DB"
    },{
        "id": 3,
        "name": "Jack",
        "city": "Kolkata",
    "gender":"Male",
    "department":"Web"
    }]
}

Now, start the JSON server using the following command.

json-server --watch Employee.json

Our JSON server is started at port: 3000 and URL is: http://localhost:3000/employees

Step 5: Setup HttpClient for service.

Angular is full Frontend Framework, so it has already HTTP module. So first let us configure inside app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

 imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    HttpClientModule,
],

Now, create models folder and inside models folder, create one file called employee.model.ts. It is a class, which tells the Angular 6 application that, which kind of data is on the back end that we need to display at front end.

// employee.model.ts

export class Employee {
    id: number;
    name: string;
    city: string;
    gender: string;
    department: string;
}

Here, inside employees folder, create one file called employee.service.ts. We are writing the network request code inside this file.

// employee.service.ts. 

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class EmployeeService {
    API_URL = 'http://localhost:3000';
    constructor(private httpClient: HttpClient) { }
    getEmployees() {
        return this.httpClient.get(`${this.API_URL}/employees`);
    }
}

Now, import employee.service.ts service file and employee.model.ts model file inside list-employees.component.ts file.

// list-employees.component.ts

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

@Component({
  selector: 'app-list-employees',
  templateUrl: './list-employees.component.html',
  styleUrls: ['./list-employees.component.css']
})
export class ListEmployeesComponent implements OnInit {
  employees: Employee[];
  constructor(private _employeeService: EmployeeService) { }

  ngOnInit() {
    this.getEmployees();
  }

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

Loop through that data and display it as a HTML table inside list-employees.component.html file.

// list-employees.component.html 
<table class="table table-bordered">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>City</th>
            <th>Gender</th>
            <th>Department</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let employee of employees">
            <td>{{employee.id}}</td>
            <td>{{employee.name}}</td>
            <td>{{employee.city}}</td>
            <td>{{employee.gender}}</td>
            <td>{{employee.department}}</td>
        </tr>
    </tbody>
</table>

Save the file and check the browser on http://localhost:4200/. You can see the data is rendered in Employee List page.

Click on Add Employee link. You can see the page with message.

Currently Add Employee page has not any form or functionality added.

Summary

So, this is the Part 1 of Angular 6 CRUD, we have seen the following concepts.

  1. Angular 6 Development Environment
  2. Angular 6 Configure Routing and Navigation for components.
  3. Create a JSON server that serves the data.
  4. Angular 6 HTTP Get request with service example
  5. Angular 6 Reading data from service and display on UI.

In part 2 of Angular 6 CRUD, we will discuss about Angular 6 forms with validations and apply remaining functionalities like Add Employee, Update Employee and Delete Employee.

Nisarg Dave
Nisarg Dave

He works as a software developer. He has hands-on experience on .net and other Microsoft technologies. He also works on AngularJS, KnockOutJS.

Views: 37,801

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to email a link to a friend (Opens in new window) Email
  • Click to print (Opens in new window) Print

Like this:

Like Loading...

Related Posts

Total
0
Shares
Share 0
Tweet 0
Pin it 0
21 comments
  1. Anonymous says:
    May 9, 2018 at 8:37 am

    Doing great job

    Reply
  2. Rk says:
    May 9, 2018 at 5:11 pm

    Helpful tutorial..

    Reply
  3. Ben Roger says:
    May 9, 2018 at 5:29 pm

    Nicely explained, eagerly waiting for part 2 and many more

    Reply
  4. Anonymous says:
    June 18, 2018 at 6:53 pm

    Always getting this Error. not able to found this- core.js:1542
    ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: “Not Found”, url: “http://localhost:4200/$%7Bthis.API_URL%7D/employees”, ok: false, …}
    Cannot GET /$%7Bthis.API_URL%7D/employees
    Http failure response for http://localhost:4200/$%7Bthis.API_URL%7D/employees: 404 Not Found”name: “HttpErrorResponse”ok: falsestatus: 404statusText: “Not Found”url: “http://localhost:4200/$%7Bthis.API_URL%7D/employees”__proto__: HttpResponseBase

    Reply
    1. Nisarg Dave says:
      July 5, 2018 at 6:20 pm

      I think your JSON server is not started. You need to start JSON server using ‘json-server –watch Employee.json’ command in command prompt.

      Reply
      1. Ravitej says:
        July 9, 2018 at 12:41 pm

        Sir, Kindly upload Part2 for Updation and deletion Operations also

        Reply
  5. Rush says:
    July 4, 2018 at 4:34 am

    Thanks for this tutorial. When will you be uploading part 2 for this tutorial?

    Reply
  6. Ravitej says:
    July 9, 2018 at 12:40 pm

    Where is the part2 link for updation and deleteion operations…. Plz msg

    Reply
  7. Robert says:
    August 10, 2018 at 1:58 am

    no data is returned in the browser.
    Which folder are we supposed to put Employee.json in ?

    Reply
  8. Anonymous says:
    October 22, 2018 at 6:03 pm

    where is part 2??

    Reply
  9. deepak says:
    December 8, 2018 at 12:43 am

    where is the part 2?

    Reply
  10. Sreejith says:
    December 26, 2018 at 5:25 pm

    please share the part 2

    Reply
  11. Anonymous says:
    January 15, 2019 at 4:02 pm

    Wating for part 2 please Upload as fast as possible

    Reply
  12. Anonymous says:
    February 11, 2019 at 12:01 pm

    part 2 send mi

    Reply
  13. Ajit kumar singh says:
    March 5, 2019 at 6:36 pm

    Sir where is part2 please provide part2

    Reply
  14. WI EM says:
    March 6, 2019 at 4:26 pm

    part 2 please

    Reply
  15. Anonymous says:
    April 5, 2019 at 6:15 pm

    can u upload part2

    Reply
  16. Anonymous says:
    August 12, 2019 at 12:51 am

    eagrly waiting for part2…please upload and help us

    Reply
  17. Anonymous says:
    August 18, 2019 at 6:34 pm

    part 2 podura venna

    Reply
  18. mukesh says:
    September 19, 2019 at 1:18 pm

    Sir json dummy data are not show on a using the http://localhost:4200/list

    Reply
  19. Deepak Singh says:
    September 24, 2019 at 6:23 pm

    Nice Example! Waiting for Part 2

    Reply

Leave a ReplyCancel reply

Subscribe to Website via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Posts
  • Getting Started with AWS Step Functions: Orchestration Made Simple

    Getting Started with AWS Step Functions: Orchestration Made Simple

    3 weeks ago
  • React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    1 year ago
  • Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    2 years ago
  • Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    2 years ago
  • Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    2 years ago
  • Angular Custom Elements: Creating Reusable Components with Angular

    Angular Custom Elements: Creating Reusable Components with Angular

    2 years ago
  • Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    5 years ago
  • How to Build an Inclusive Esports Community

    How to Build an Inclusive Esports Community

    5 years ago
  • Best Digital Icebreakers

    Best Digital Icebreakers

    5 years ago
  • Email alerts when a docker container stopped in AWS ECS CLUSTER

    Email alerts when a docker container stopped in AWS ECS CLUSTER

    5 years ago
Subscribe to Website via Email

Enter your email address to subscribe to this website and receive notifications of new posts by email.

Featured Posts
  • javascript 1
    Spread syntax (three dots) in JavaScript
    • March 21, 2018
  • Angular 2
    Angular 6 CRUD – Part 1: Project Setup, Routing, Service
    • May 9, 2018
  • javascript 3
    Local Storage and Session Storage
    • May 22, 2017
  • Angular 4
    Angular 4 Project Structure
    • June 18, 2017
  • AWS 5
    Email alerts when a docker container stopped in AWS ECS CLUSTER
    • July 24, 2020
Code4Developers
Learning is never ending process

Input your search keywords and press Enter.

 

Loading Comments...
 

    %d