In this tutorial, you’ll learn how to get started with creating a web app using Angular 4, Node.js & MongoDB. This tutorial assumes the reader to have basic knowledge of JavaScript programming language and JSON ( JavaScript Object Notation ).

Other tutorials in the Angular Web Series:

What is Angular ?

Angular is a web development platform developed by Google for creating progressive web apps. Angular 1.x was and is quite popular among web application developers. The latest version of Angular released by Google is Angular 4 which is based on components. Unlike the prior version of Angular it does have the concept of scope and controllers. Although JavaScript is also supported by Angular, they recommend the use of TypeScript language when using Angular platform.

From the official documentation,

Angular is a platform that makes it easy to build applications with the web. Angular combines declarative templates, dependency injection, end to end tooling, and integrated best practices to solve development challenges. Angular empowers developers to build applications that live on the web, mobile, or the desktop.

Source code from this tutorial is available on GitHub.

Creating A Web App Using Angular 4

To get started with creating a web app using Angular 4, you need to install the Angular CLI.

npm install -g @angular/cli

Once the Angular CLI has been installed, you need to create the application using the following command:

ng new GroceryApp

After the application has been created, navigate to the project directory and run the Angular application.

ng serve

Point your browser to http://localhost:4200 and you should be able to view the default application running.

Now if you have a look at the source code of the default application, you can see that you have a index.html page where you have the loaded the app-root component. By default the application has only the app-root component which is defined inside the src/app folder. Here is how the application source code path looks like:

Web App Using Angular

You’ll keep the AppComponent as the parent component and load our components inside the AppComponent.

Let’s start by adding the basic HTML template file for the AppComponent. Modify the existing HTML code inside the app.component.html as shown:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 
</head>

<body>
  <div class="container">
    <div class="header clearfix">
      <nav>
        <ul class="nav nav-pills float-right">
          <li class="nav-item">
            <a data-toggle="modal" data-target="#exampleModalLong" class="nav-link active" href="#">Add <span class="sr-only">(current)</span></a>
          </li>
        </ul>
      </nav>
      <h3 class="text-muted">Grocery manager</h3>
    </div>
  </div>
  <!-- /container -->
</body>

</html>

You’ll be using bootstrap for the styling the application. Download and include the bootstrap files as shown inside the angular-cli.json.

"styles": [
    "styles.css",
    "assets/bootstrap.min.css"
],
"scripts": [
    "assets/jquery.min.js",
    "assets/popper.min.js",
    "assets/bootstrap.min.js"
]

Save the changes and try running the app and you should have the screen as shown:

web app using angular

Creating the Grocery Listing Component

Let’s start by creating the basic structure for the Grocery Listing Component. Inside the src/app folder create a folder called grocerylist. Inside grocerylist folder create a file called grocerylist.component.html and add the following HTML code:

Create a file called grocerylist.component.css and add the following the following code:

.listContainer{
  border: 1px solid rgb(187, 170, 170);
  border-radius: 10px;
  padding: 30px;
}

Create a file called grocerylist.component.ts file and add the following code:

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

@Component({
  selector: 'grocery-list',
  templateUrl: './grocerylist.component.html',
  styleUrls: ['./grocerylist.component.css']
})
export class GroceryListComponent implements OnInit {

    constructor(){

    }

    ngOnInit(){
        
    }
}

As seen in the above code, you have created the GroceryListComponent with the templateUrl pointing towards the grocerylist.component.html and style pointing towards grocerylist.component.css. You can use the GroceryListComponent using the grocery-list selector.

Creating the Add Grocery Component

Now let’s create the Angular component to add a grocery item to the list. Start by creating a folder called groceryadd to the src/app folder. Add a file called groceryadd.component.html file. Here is how it looks:

<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Add Item</h5>
      </div>
      <div class="modal-body">
        <input class="form-control" [(ngModel)]="groceryItem" id="ex1" type="text">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" (click)="addGrocery()" data-dismiss="modal" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

As seen in the above code, you have binded the input text field with a groceryItem variable which will help in two way data binding.

Add the component typescript file called groceryadd.component.ts which would handle the component logic.

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

@Component({
    selector: 'grocery-add',
    templateUrl: './groceryadd.component.html',
    styleUrls: ['./groceryadd.component.css']

})
export class GroceryAddComponent implements OnInit {

    private groceryItem


    constructor(private commonService:CommonService) {

    }

    addGrocery(){
        
    }

    ngOnInit() {

    }
}

Now let’s register both of your components in the app.module.ts file. In order to do that first you need to import both the components and then add in the import list. Here is how it looks like:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { GroceryAddComponent } from './groceryadd/groceryadd.component'
import { GroceryListComponent } from './grocerylist/grocerylist.component'

@NgModule({
  declarations: [
    AppComponent,
    GroceryAddComponent,
    GroceryListComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now let’s use the above components in the app.component.html template.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 
</head>

<body>
  <div class="container">
    <div class="header clearfix">
      <nav>
        <ul class="nav nav-pills float-right">
          <li class="nav-item">
            <a data-toggle="modal" data-target="#exampleModalLong" class="nav-link active" href="#">Add <span class="sr-only">(current)</span></a>
          </li>
        </ul>
      </nav>
      <h3 class="text-muted">Grocery manager</h3>
    </div>
    
    <grocery-list></grocery-list>
    <grocery-add></grocery-add>
  </div>
</body>

</html>  

Save the above changes and restart the server. Try clicking on the Add button on the screen and you should have the Add Grocery Item popup on the screen.

Angular Grocery PopUp

Adding the Grocery Item to the List

Create a common service which will help in adding the items to the grocery list and intimate the grocery listing component about the change. Here is how the common.service.ts file looks like:

import { Injectable } from '@angular/core';
import { Grocery } from '../groceryadd/grocery.model'
import { Subject } from 'rxjs/Subject';

@Injectable()
export class CommonService {
    public groceryList: Grocery[]
    public add_subject=new Subject()

    constructor(){
        this.groceryList = []
    }

    addGrocery(item){
        this.groceryList.push(new Grocery(item,false))
        this.add_subject.next()
    }
}

As seen in the above code, the common service has groceryList to which the items are added using the addGrocery method. Each time a new entry is added to the list the add_subject informs its subscriber in the GroceryListComponent. Here is how you’ll subscribe to add_subject in the ngOnInit method in GroceryListComponent:

    ngOnInit(){
        this.commonService.add_subject.subscribe(response => {
            this.groceryList = this.commonService.groceryList
        })
    }

Here is the GroceryAddComponent class with the addGrocery method :

export class GroceryAddComponent implements OnInit {

    private groceryItem


    constructor(private commonService:CommonService) {

    }

    addGrocery(){
        this.commonService.addGrocery(this.groceryItem)
        this.groceryItem = ''
    }

    ngOnInit() {

    }
}

Also modify the grocerylist.component.html code to iterate over the groceryList and dynamically create the li element.

Save the above changes and try running the code and you should be able to add items to the grocery list.

Angular Grocery App Listing

Wrapping It Up

In this tutorial, you learnt how to get started with creating a web app using Angular 4. In this part your created the UI using Angular. In the next and final part of the tutorial, you’ll learn to save the data to MongoDb using Node.js.

Do let us know your thoughts, suggestions or any corrections in the comments below.

Source code from this tutorial is available on GitHub.