Angular – Basic Components, Setup, and Routing

Photo by Tara Winstead from Pexels

Introduction

The article is a step by step on how to create a simple Angular SPA. It will go over what you need to install and how to generate components and to configure the application to run the most common libraries.

Prerequisites

Download and install NPM (Node Package Manager). We will use this to install Angular.

URL to download NPM (NodeJS) https://nodejs.org/en/download/

Check if NPM is installed by typing the following

NPM -Version

Now install Angular with the folllowing NPM

npm install -g @angular/cli

Check if you can get to the CLI (Command Line Interface).

ng –version

You should see something similar to the following:

Create a New Application

Type the following commands.

ng new myFirstApp

Choose yes for routing

Pick SCSS using your up and down arrow keys.

Go into the new project folder that was created and run the application

Change directory into the new application “myFirstApp”.

cd myFirstApp

Run the application

ng serve --open OR ng s --open

If port 4200 is not available then type the following

ng s --port=4202

Open your browser and type localhost:4200 in the address bar.

Your folder structure should look like the following. The code for the root component of the application is under src –> app

These are the files created for you to start with. Some may not be there but that is OK we can add them later. This is the root component.

Now lets add 2 components by using the following commands

Note: ng g c is the same as ng generate component

ng g c comp-one
ng g c comp-two

You should see the two new components you just built.

Configure the Root Application Module

Open the apps.module.ts under the “\app” folder and add a few base libraries for browser animations, routing, reactive forms, and http client services.

Add the following to the imports block in apps.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientJsonpModule, HttpClientModule } from '@angular/common/http';

The Imports under declarations (below) have the basic imports a typical Angular application SPA would need to run with Reactive Forms.

@NgModule({
  declarations: [
    AppComponent,
    CompOneComponent,
    CompTwoComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    HttpClientModule,
    HttpClientJsonpModule,
    BrowserAnimationsModule,
    FormsModule  

  ],
  providers: [],
  entryComponents: [
      // Material Bottom Sheets and Dialog Entry Components    
 ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Enable the Router at the Root Component

Second go to the apps.component.html and replace the html with the following so we can use the router. Replace all of the code in there with the following:

<router-outlet #outlet="outlet"></router-outlet>

Set Up The Routes

Open app-routing.module.ts and add the following imports and code to the file.

Import the component libraries:

import { CompTwoComponent } from './comp-two/comp-two.component';
import { CompOneComponent } from './comp-one/comp-one.component';

Paths

Now we can add the following routes

{
  path: '',
  component: CompOneComponent
},
{
  path: 'home',
  component: CompTwoComponent
}

All Together

Your apps.routing.module.ts should look like the following;

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CompTwoComponent } from './comp-two/comp-two.component';
import { CompOneComponent } from './comp-one/comp-one.component';

const routes: Routes = [
  {
    path: '',
    component: CompOneComponent
  },
  {
    path: 'home',
    component: CompTwoComponent
  }
]

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

Try It

From your browser try localhost:4202 you should see

comp-one works!

Then try the route localhost:4202/home and you should see

comp-two works!

Binding

Now lets try binding a property.

From your comp-one.component.ts file add the following to your code;

title: string;

Inside ngOnInit() add the following:

this.title = 'Hello Angular';

Your comp-two.component.ts should look like the following:

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

@Component({
  selector: 'app-comp-two',
  templateUrl: './comp-two.component.html',
  styleUrls: ['./comp-two.component.scss']
})
export class CompTwoComponent implements OnInit {

  title: string;
  constructor() { }

  ngOnInit() {
    this.title = 'Hello Angular';
  }
}

Now open the comp-two.component.html file and add the following:

<p>comp-two works!</p>
Title: {{title}}

You should see the following:

Function Example

From comp-two.component.ts

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

@Component({
  selector: 'app-comp-two',
  templateUrl: './comp-two.component.html',
  styleUrls: ['./comp-two.component.scss']
})
export class CompTwoComponent implements OnInit {

  title: string;
  max: number;
  constructor() { }

  randomNumbers() {
    return Math.floor(Math.random() * Math.floor(this.max));
  }

  ngOnInit() {
    this.title = 'Hello Angular';
    this.max = 120;
  }
}

From comp-two.component.html

<p>comp-two works!</p>
Title: {{title}} Random Number Function Call {{randomNumbers()}}

Now you should see the following: