AppDividend
Latest Code Tutorials

Angular 6 Tutorial With Example using Angular CLI

3 2,414

Get real time updates directly on you device, subscribe now.

Angular 6 Tutorial With Example using Angular CLI is the topic, we discuss today. Angular is One framework for Mobile & desktop. Angular puts you in control over scalability. Meet substantial data requirements by building data models on RxJS, Immutable.js or another push-model. We start this tutorial by installing Angular using Angular CLI and then working on our tutorial.

Angular 6 Tutorial

First, we need to set up a development environment.

Step 1: Set up the Development Environment.

Install Node.js® and npm if they are not already on your machine.

Then install the Angular CLI globally.

# run in administrator mode

sudo npm install -g @angular/cli

# or

yarn add global @angular/cli

The Angular CLI installs the necessary npm packages, creates the project files, and populates the project with a simple default app. Installation can take some time.

Now, create a boilerplate project using the following command.

ng new ngtutorial

Angular 6 Tutorial With Example using Angular CLI

So, now the project is initialized. Go into our project folder. 
cd ngtutorial

Open the project in your editor; I am using VSCode.

code .

Also, start the development server by the following command.

ng serve

Angular 6 Example

Step 2: Install Bootstrap 4 in an Angular app.

Go to your root and install bootstrap 4 using the following command.

yarn add bootstrap

Okay, now copy the bootstrap.min.css file from node_modules/bootstrap/dist/css folder to src/assets/css folder. If the CSS folder is not there, then create one and add that bootstrap.min.css file in it. Now, add the link to that CSS file inside src  >> index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Ngtutorial</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>

Now, you have successfully integrated the Bootstrap 4 Framework.

Step 3: Configure Routing for our components.

Now, create two components using the following command.

ng g c dashboard

Moreover, create another component.

ng g c users

Angular automatically update the app.module.ts file.

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.

I am writing the whole code inside app.module.ts file.

Related Posts
1 of 9
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { UsersComponent } from './users/users.component';

const routes: Routes = [
  { path: 'users', component: UsersComponent },
  { path: 'dashboard', component: DashboardComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    UsersComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

First, we have included the RouterModule and Routes module.

Next, we have created the routes array which is the type of Routes.

That array contains an object, and the properties are following.

  1. path
  2. component

Add an @NgModule.exports array with inRouterModule it. Exporting RouterModule makes router directives available for use in the components AppModule that will need them.

Okay, now we need to display the output of the different routes. For that, we need to define a <router-outlet> component. Also, we need to create a navbar, 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 application.

<!--The content below is only a placeholder and can be replaced.-->
<div id="app">
    <nav class="navbar navbar-expand-sm bg-light">
        <ul class="navbar-nav">
        <li class="nav-item">
            <a routerLink="/" class="nav-link">Home</a>
        </li>
        <li class="nav-item">
            <a routerLink="/dashboard" class="nav-link">Dashboard</a>
        </li>
        <li class="nav-item">
            <a routerLink="/users" class="nav-link">Users</a>
        </li>
        </ul>
    </nav>
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</div>

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 I am using one package called json-server for this tutorial. Okay, so let us install the package using Yarn package manager.

yarn global add json-server

# or

npm install -g json-server

Now we need to create a folder inside src directory called data and in that folder, create one file called db.json. Let us add the following data inside a db.json file.

{
    "results": [
    {
        "id": "1",
        "name": "RDJ",
        "movies": "100"
    },
    {
        "id": "2",
        "name": "Tom Holland",
        "movies": "3"
    },
    {
        "id": "3",
        "name": "Benedict Cumberbatch",
        "movies": "10"
    },
    {
        "id": "4",
        "name": "Chris Hemsworth",
        "movies": "30"
    },
    {
        "id": "5",
        "name": "Chris Evans",
        "movies": "20"
    }]
}

Now, start the JSON server using the following command.

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

Now, we have a server running that can feed the data to our React Bootstrap Application.

Our JSON server is started at port: 4000 and URL is: http://localhost:4000/results

Step 5: Setup HttpClient.

In other Frontend libraries like React and Vue, we need to install third-party network request library like Axios or Fetch. However, it is not the case in Angular. Angular is full fledge 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, inside users folder, create one file called User.ts. It is an interface, which tells the Angular application that, which kind of data is on the backend that we need to display at frontend.

// User.ts

export interface User {
    id: Number;
    name: String;
    movies: Number;
  }

Also, inside users folder, create one file called user.service.ts. We are writing the network request code inside this file. Then we import this file inside user.component.ts file and then call service file’s function.

// user.service.ts

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

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

Now, include this file inside users.component.ts file.

// users.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
import { User } from './User';

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

  users: User[];

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService
      .getUsers()
      .subscribe((data: User[]) => {
          this.users = data;
        });
  }

}

Loop through that data and display it as a table inside the users.component.html file.

<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Movies</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users">
      <td>{{ user.id }}</td>
      <td>{{ user.name }}</td>
      <td>{{ user.movies }}</td>
    </tr>
  </tbody>
</table>

 

Angular HTTP Get request tutorial

So, in this simple tutorial, we have seen the following concepts.

  1. Angular 6 Routing
  2. Angular 6 HTTP Get Request
  3. Angular 6 Service Example

Finally, Angular 6 Tutorial With Example using Angular CLI is over. Thanks for taking this example.

3 Comments
  1. Rustem says

    core.js:1449 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[UsersComponent -> UserService]:
    StaticInjectorError(Platform: core)[UsersComponent -> UserService]:
    NullInjectorError: No provider for UserService!
    Error: StaticInjectorError(AppModule)[UsersComponent -> UserService]:
    StaticInjectorError(Platform: core)[UsersComponent -> UserService]:
    NullInjectorError: No provider for UserService!

    1. Nemanja says

      Please include in your code!

      app.module.ts :

      import { UserService } from ‘./users/user.service’;

      @NgModule({

      providers: [UserService],

      })
      export class AppModule { }

      1. Derek says

        Thanks this worked for me.

Leave A Reply

Your email address will not be published.