create account

MEAN Tutorial Part 4 - Frontend Navigation Bar by nafestw

View this thread on: hive.blogpeakd.comecency.com
· @nafestw · (edited)
$20.26
MEAN Tutorial Part 4 - Frontend Navigation Bar
![logo_part4.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970841/f6dwvb1iqgw7x2pe7wq6.png)

> This tutorial series shows how to build web applications with the MEAN stack. The MEAN stack is [MongoDB](https://www.mongodb.com/), [Express.js](http://expressjs.com/), [Angular](https://angular.io/), and [Node.js](https://nodejs.org/en/). This stack allows to write applications, where Javascript can be used both for the client and the server part.
> In this tutorial a simple webapplication to manage portfolios of cryptocurrencies such as Bitcoin or Ethereum will be built. 

#### What will I learn?

In this part of the tutorial series
- you will learn to create a Angular application with Angular CLI, and
- you will learn to create basic navigation on the web frontend.

#### Requirements
For this part of the tutorial you need the following background knowledge:
- Previous parts of this series
- Working with the command line
- Experience in TypeScript, JavaScript, HTML, and CSS

#### Difficulty

Intermediate.

#### Tutorial contents
In this part of the tutorial we finally start with the frontend for the server code developed in the last parts of this series. We will use Angular CLI to create an Angular application and components for navigation, login, and registration.

##### What is Angular?
> Angular is a framework for building client applications in HTML and either JavaScript or a language like TypeScript that compiles to JavaScript.

>You write Angular applications by composing HTML templates with Angularized markup, writing component classes to manage those templates, adding application logic in services, and boxing components and services in modules.

(from [angular.io](https://angular.io/guide/architecture))

##### Install @angular/cli
Creating an Angular frontend requires a lot of boilerplate code which is tedious to write. Fortunately there is a `npm` package that provides a command line interface to simplify the development of Angular applications: [Angular CLI](https://cli.angular.io). Install it globally on your system with

    npm install -g @angular/cli@1

Now you may use the `ng` command to create, generate, and serve the frontend.

##### Create and run the frontend framework
Start with creating a new Angular application. Go to the base folder of our application created in the previous lessons and enter

    ng new frontend

This creates a new subfolder `frontend` with an independent node project with its own `package.json` and its own `node_modules` folder for its dependencies. If you already setup a git repository for your project, `ng` detects that and only creates a `.gitignore` file in the new folder, otherwise it initializes a new git repository for the frontend.

The entry point of the generated Angular application is `frontend/src/main.ts`, which basically only bootstraps the app module in `frontend/src/app`. In this folder you find the implementation of this module in `app.module.ts` and the component `app.component`. An Angular component corresponds to a web page or a part of a web page (e.g. the navigation part).

The generated application is already complete and can be run by executing `ng serve` in the `frontend` folder. On the first run some files are compiled, but after a few seconds the server should be up and running and you can access it in your browser with `http://localhost:4200`.

![welcome_shadow.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970866/dhwjaqfflzv0l4vxvhf0.png)

##### Import Bootstrap
Bootstrap is an open-source library for designing web front ends originally developed by Twitter. We use it since it provides ready-to-use CSS classes for navigation bars and for buttons. The index file in `frontend/src` is the main template for all sites served by Angular. Replace the contents of this file with the following modified version of the [starter template code from Bootstrap](https://getbootstrap.com/docs/4.0/getting-started/introduction/):

````
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>MEAN Tutorial</title>
  </head>
  <body>
    <base href="/">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <app-root></app-root>
  </body>
</html>
````
Note, that the only thing that we kept from the generated file is `<app-root></app-root>`, which includes the main application component. This is part of Angular's templating engine and includes the template for the app component in `src/app/app.component.html`.

If you kept `ng serve` running, you will notice that the frontend in your browser updated, as soon as you saved the changes to `index.html`. The contents did't change, as they are part of the app component, but the styling, due to the import of the BootStrap CSS.

##### Add a navigation bar
Now we will get rid of the template code displayed by the app component and replace it with a navigation bar. For the navigation bar, create a new Angular component by executing

    ng g component nav-bar

in the frontend folder. `g` stands for generate. Since a navigation bar is pretty useless without places to navigate to, create two additional components for the registration and login pages with

    ng g component register
    ng g component login

Note that Angular CLI creates a subfolder in `frontend/src/app` for every new component with four files in it.

![files.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970899/tb4zj0tugtno4jk9co8x.png)

The `.html` file contains the HTML template for the component, the `.ts` the implementation of the component's class, the `.spec.ts` contains tests and the `.css` may contain additional stylesheets. We will ignore the later two for now and only work with the HTML templates and the component's class implementations.

Angular uses TypeScript (that's what the `.ts` stands for), which is a strict superset of JavaScript, that adds optional static typing. All JavaScript code is valid TypeScript code. Since TypeScript is not supported by browsers it is compiled to browser compatible JavaScript as soon as you run `ng serve`.

Open the HTML template for the nav-bar component (`frontend/app/nav-bar/nav-bar.component.html`) and replace its contents with

````
<nav class="navbar navbar-expand-sm navbar-light bg-primary">
  <a class="navbar-brand">MEAN Tutorial</a>
  <ul class="navbar-nav ml-auto">
    <li class="nav-item">
      <a class="nav-link" routerLinkActive="active" routerLink="/login">Login</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" routerLinkActive="active" routerLink="/register">Register</a>
    </li>
  </ul>
</nav>
````

This creates a navigation bar with a brand item on the left and two login/register items at the right. All CSS classes used in this snippet are provided by Bootstrap. The login and register anchor tags use two special attributes: `routerLink` and `routerLinkActive`. These are two selectors provided by the Angular's Router module which we will use below in the app component class. With `routerLink`, we set the target route for the link. With `routerLinkActive` we specify a CSS class for the link that is currently active. This way the last selected item of the navigation bar will be highlighted.

Since we don't have instantiated a router yet, nothing will happen, if you click on Login or Register. To add the router, first import the router module in the main app module. Open `frontend/src/app/app.module.ts` and insert the following import below the import of NgModule:

````
import { RouterModule, Routes } from "@angular/router";
````

Now create a two element sized array of Routes with the `/register` and `/login` routes below the import statements. 
````
const routes: Routes = [
  { path: "register", component: RegisterComponent },
  { path: "login", component: LoginComponent }
];
````
This links the route for `/register` to the `RegisterComponent` and the route for `/login` to the `LoginComponent`. Finally, add the router to the module's list of imports after the BrowserModule:
````
 imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
 
````
The one thing still missing is an outlet for the router in the app component's HTML template. Therefore, we get rid of the generated boilerplate in `app.component.html` and replace it with the following code.

````
<app-nav-bar></app-nav-bar>
<div class="container">
  <router-outlet></router-outlet>
</div>
````
On top of every page of our app, the navigation bar should be rendered, hence the template of `<app-nav-bar>` is included on top. The outlet of the router is placed in a BootStrap container `<div>` below.

The router also needs to know, how to compose the navigation URLs. Therefore we already added a `<base href="/">` in `index.html` above.

With this, you should be able to switch between the Login and Register components by clicking on the links in the navigation bar. The default template for these components should display `login works` and `register works` respectively.

![login_works_shadow.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970918/yxbb2hkpjolveyuuax76.png)

This concludes the fourth part of the tutorial series on how to build a web application with the MEAN web application stack.

#### Example Code on Github
The code for this part of the tutorial can be found on [Github](https://github.com/nafest/mean_tutorial/tree/master/lesson4).

#### What's next?
In the next part we will continue with implementing the registration and login components.

#### Curriculum
Previous parts of this series:
* [Part 1 - Get started with the MEAN development stack](https://utopian.io/u/29269006)
* [Part 2 - Adding a user model](https://utopian.io/u/30330541)
* [Part 3 - Registration and Authorization](https://utopian.io/u/31501980)

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@nafestw/mean-tutorial-part-4-frontend-navigation-bar">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , ,
properties (23)
authornafestw
permlinkmean-tutorial-part-4-frontend-navigation-bar
categoryutopian-io
json_metadata{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":27193779,"name":"node","full_name":"nodejs/node","html_url":"https://github.com/nodejs/node","fork":false,"owner":{"login":"nodejs"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","nodejs","angular","programming","javascript"],"users":["angular","1"],"links":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970841/f6dwvb1iqgw7x2pe7wq6.png","https://www.mongodb.com/","http://expressjs.com/","https://angular.io/","https://nodejs.org/en/","https://angular.io/guide/architecture","https://cli.angular.io","https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970866/dhwjaqfflzv0l4vxvhf0.png","https://getbootstrap.com/docs/4.0/getting-started/introduction/","https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970899/tb4zj0tugtno4jk9co8x.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970918/yxbb2hkpjolveyuuax76.png","https://github.com/nafest/mean_tutorial/tree/master/lesson4","https://utopian.io/u/29269006","https://utopian.io/u/30330541","https://utopian.io/u/31501980"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970841/f6dwvb1iqgw7x2pe7wq6.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970866/dhwjaqfflzv0l4vxvhf0.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970899/tb4zj0tugtno4jk9co8x.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1518970918/yxbb2hkpjolveyuuax76.png"],"moderator":{"account":"yokunjon","time":"2018-02-19T08:57:39.839Z","reviewed":true,"pending":false,"flagged":false},"questions":[],"score":0}
created2018-02-18 16:35:00
last_update2018-02-19 08:57:39
depth0
children2
last_payout2018-02-25 16:35:00
cashout_time1969-12-31 23:59:59
total_payout_value14.034 HBD
curator_payout_value6.226 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length10,805
author_reputation2,113,027,036,393
root_title"MEAN Tutorial Part 4 - Frontend Navigation Bar"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id38,557,218
net_rshares4,428,614,834,570
author_curate_reward""
vote details (7)
@utopian-io ·
### Hey @nafestw I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Suggestions
- Contribute more often to get higher and higher rewards. I wish to see you often!
- Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!
#### Get Noticed!
- Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-nafestw-mean-tutorial-part-4-frontend-navigation-bar-20180219t180024998z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-02-19 18:00:24
last_update2018-02-19 18:00:24
depth1
children0
last_payout2018-02-26 18:00:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,505
author_reputation152,955,367,999,756
root_title"MEAN Tutorial Part 4 - Frontend Navigation Bar"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id38,848,847
net_rshares0
@yokunjon ·
Thank you for the contribution. It has been approved.

* We prefer tutorials as a whole as possible instead of dozens of parts. So, next time, please merge some topics together.

You can contact us on [Discord](https://discord.gg/uTyJkNm).

**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authoryokunjon
permlinkre-nafestw-mean-tutorial-part-4-frontend-navigation-bar-20180219t090220895z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-02-19 09:03:48
last_update2018-02-19 09:03:48
depth1
children0
last_payout2018-02-26 09:03:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length297
author_reputation19,266,807,595,513
root_title"MEAN Tutorial Part 4 - Frontend Navigation Bar"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id38,738,611
net_rshares0