We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

Learn how to – How To Manage Angular JS Projects using Angular CLI

Learn how to – How To Manage Angular JS Projects using Angular CLI.

In the world today, there are various software products we rely on. These include Facebook, WhatsApp, Instagram etc. Do you know that all these products were carefully developed and programmed by developers using different languages?

Programming can be defined as the process of giving a computer/machine a set of instructions to execute. These can be instructions on how to carry out a specific task. Since there are several programming languages, programmers spend most of their time learning a variety of programming languages and tools so they can effectively build computer programs. Popular programming languages are Python, Java, Ruby, PHP, C/C++, JavaScript and C#.

AngularJS is an open-source web application framework that allows users to create interactive components of a website. It lets developers use HTML as their template language and extend the HTML’s syntax to express their application’s components clearly and succinctly. This framework was developed by Misko Hevery and Adam Abrons in 2009 and is currently maintained by Google.  Today, there are a lot of reputable development services including Expert Remote that help build single-page applications using AngularJS.

AngularJS is prefered due to the following features and benefits:

  • Applications written in AngularJS can run on all major browsers and smartphones, including Android and iOS-based phones/tablets. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is free and open-source and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.
  • It provides developers options to write client-side applications using JavaScript in a clean Model View Controller (MVC) way.
  • It is an efficient framework that can create Rich Internet Applications (RIA). The developers can achieve more functionality with shortcodes. It also provides reusable components.
  • It provides data binding capability to HTML, thus, giving users a rich and responsive experience.

Angular CLI is a command-line utility tool that makes it easy to initialize, develop, scaffold, and maintain AngularJS applications. It uses Webpack to include all the packaging, importing, BrowserLink etc. Webpack handles the importing of 3rd party libraries for your Angular project and turns them into modules automatically.

This guide explains how to manage Angular JS Projects using Angular CLI.

Before You Begin

For this guide, you need to have:

  • knowledge of the terminal or Command Line Interface, TypeScript and familiarity with CSS and HTML, JavaScript
  • You also need to have an active LTS or maintenance LTS version of Node.js since the Angular CLI, and Angular applications depend on npm packages.

To install Node.js, use the guides below:

Once installed, check the version:

$ node  -v
v16.18.1

$ npm -v
8.19.2

#1. Install Angular CLI on Your System

Once you have Node.js installed, it is easy to install the Angular CLI. It will be used to create, and generate application and library code for Angular JS. You will also be able to perform a variety of ongoing development tasks such as testing, bundling, and deployment.

To install Angular CLI, use the command below:

sudo npm install -g @angular/cli

Once the installation is complete, check the version using the command:

$ ng version
? Would you like to enable autocompletion? This will set up your terminal so pressing TAB while typing Angular CLI commands will show possible options and autocomplete 
arguments. (Enabling autocompletion will modify configuration files in your home directory.) Yes
Appended `source <(ng completion script)` to `/home/ubuntu/.bashrc`. Restart your terminal or run the following to autocomplete `ng` commands:

    source <(ng completion script)
? Would you like to share pseudonymous usage data about this project with the Angular Team
at Google under Google's Privacy Policy at https://policies.google.com/privacy. For more
details and how to change this setting, see https://angular.io/analytics. No
Global setting: disabled
Local setting: No local workspace configuration file.
Effective status: disabled

     _                      _                 ____ _     ___
    /    _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △  | '_  / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ | | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   __| |_|__, |__,_|_|__,_|_|       ____|_____|___|
                |___/
    

Angular CLI: 15.0.1
Node: 16.18.1
Package Manager: npm 8.19.2
OS: linux x64

Angular: 
... 

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.1500.1 (cli-only)
@angular-devkit/core         15.0.1 (cli-only)
@angular-devkit/schematics   15.0.1 (cli-only)
@schematics/angular          15.0.1 (cli-only)

Now you are set to begin with Angular JS application development. There are several commands for the Angular CLI. They include:

COMMAND ALIAS DESCRIPTION
add Adds support for an external library to your project.
analytics Configures the gathering of Angular CLI usage metrics.
build b Compiles an Angular application or library into an output directory named dist/ at the given output path.
cache Configure persistent disk cache and retrieve cache statistics.
completion Set up Angular CLI autocompletion for your terminal.
config Retrieves or sets Angular configuration values in the angular.json file for the workspace.
deploy Invokes the deploy builder for a specified project or for the default project in the workspace.
doc d Opens the official Angular documentation (angular.io) in a browser, and searches for a given keyword.
e2e e Builds and serves an Angular application, then runs end-to-end tests.
extract-i18n Extracts i18n messages from source code.
generate g Generates and/or modifies files based on a schematic.
lint Runs linting tools on Angular application code in a given project folder.
new n Creates a new Angular workspace.
run Runs an Architect target with an optional custom builder configuration defined in your project.
serve s Builds and serves your application, rebuilding on file changes.
test t Runs unit tests in a project.
update Updates your workspace and its dependencies. See https://update.angular.io/.
version v Outputs Angular CLI version.

#2. Create an Angular JS Project

To begin work, you need to create a dedicated workspace for your Angular JS Project. For this case, we will name it sample-angular-app, however, you can give it any other preferred name.

cd ~
ng new sample-angular-app

Now the CLI will prompt you for a few stuff, here proceed as shown:

? Would you like to add Angular routing? (y/N) Y
? Which stylesheet format would you like to use?
❯ CSS
CREATE sample-angular-app/README.md (1070 bytes)
CREATE sample-angular-app/.editorconfig (274 bytes)
CREATE sample-angular-app/.gitignore (548 bytes)
CREATE sample-angular-app/angular.json (2760 bytes)
CREATE sample-angular-app/package.json (1049 bytes)
CREATE sample-angular-app/tsconfig.json (901 bytes)
CREATE sample-angular-app/tsconfig.app.json (263 bytes)
CREATE sample-angular-app/tsconfig.spec.json (273 bytes)
....
✔ Packages installed successfully.
    Successfully initialized git.

Here, we have set to use Angular routing and set CSS as the stylesheet format. Once complete, you will have all the required files, folders and NPM dependency packages generated and installed for the project.

#3. Serve the Angular JS Application

At this point, the Angular JS Application can be served on the browser using the CLI. The development server will refresh the browser in case any changes are made to the files. This ensures that the made changes reflect as soon as they are made.

To do this, navigate into the project’s root folder:

cd sample-angular-app

While here, you can serve the local development server.

ng serve --host 0.0.0.0 --port 8080

For this case, we have specified the port and set access on all interfaces. Now access the application using the URL http://IP_Address:8080

Now you can leave the development server running and open a new terminal for the below steps.

#4. Adding Angular HttpClient

It is possible to add the HttpClient to the Angular project. To do this, we need to modify the file below:

cd ~/sample-angular-app
vim src/app/app.module.ts

In the file, we will import the HttpClientModule and include it in the imports array:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

After saving the file, you can use the HttpClient service in the Angular project to consume our REST API.

#5. Creating UI Components on Angular JS

The angular applications consist of components. Here, we will learn how to create several components for the UI.

In a new terminal, navigate to the project root directory;

cd ~/sample-angular-app

While here, run the command below

ng g component home

Sample Output:

CREATE src/app/home/home.component.css (0 bytes)
CREATE src/app/home/home.component.html (19 bytes)
CREATE src/app/home/home.component.spec.ts (585 bytes)
CREATE src/app/home/home.component.ts (194 bytes)
UPDATE src/app/app.module.ts (546 bytes)

We have the 4 files generated, all these files are required by the UI component. The next step is to generate the about component:

 ng g component about

Now we will edit the about component file:

vim src/app/about/about.component.html

Modify the line as shown;

<p style="padding: 15px;"> This is the about page that describes your app</p>

After this, you should be ready for step 7

#6. Adding Routing to Angular Projects

To add routing to the project, edit the below file:

vim src/app/app-routing.module.ts

In the file, make the below adjustments:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';


const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full'},
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
];

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

In the file above, we have imported the Angular components and we declared three routes with the first route redirecting the empty path to the home component. This ensures that you are automatically redirected to the home page when you first visit the app.

#7. Adding Angular Material

We can add the Angular Material to our project and use it to build the UI. At the project root directory, execute the command:

ng add @angular/material

You will be prompted to pick the desired theme. For this case, we will choose Purple/Green:

The package @angular/material@15.0.0 will be installed and executed.
Would you like to proceed? Yes
✔ Packages successfully installed.
? Choose a prebuilt theme name, or "custom" for a custom theme: 
https://material.angular.io?theme=deeppurple-amber ] 
  Pink/Blue Grey     [ Preview: https://material.angular.io?theme=pink-bluegrey 
] 
❯ Purple/Green       [ Preview: https://material.angular.io?theme=purple-green ]
 
  Custom 
  Indigo/Pink        [ Preview: https://material.angular.io?theme=indigo-pink ]

 (Move up and down to reveal more choices)
.....

For the other questions, proceed with the defaults by pressing Enter.

Once complete, open the file below:

vim src/app/app.module.ts

In the opened file, add the below import

import { NgModule, ApplicationRef } from '@angular/core';
import { CommonModule } from '@angular/common';

import { CommonModule } from '@angular/common';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatCardModule} from '@angular/material/card';
import {MatIconModule} from '@angular/material/icon';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';

We have imported several Material Design components, some of which are:

  • MatToolbar: It provides a container for headers, titles, or actions.

  • MatCard: provides a content container for text, photos, and actions in the context of a single subject.

Still in the file, to the imports array, add the modules:

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
    CommonModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule,
    MatProgressSpinnerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now open the file below:

vim src/app/app.component.html

In the file, in the end, add the lines:

<mat-toolbar color="primary">  
<h1>  
My Angular Store  
</h1>  
<button mat-button routerLink="/">Home</button> 
<button mat-button routerLink="/about">About</button></mat-toolbar><router-outlet></router-outlet>

On the web, you will have the lines below added:

#8. Mocking a REST API

Here, we will demonstrate how to access the Angular app via a REST API. First, install the json-server.

cd ~/sample-angular-app
npm install --save json-server

Now create a server in the project root:

mkdir serve

In the folder, we will create a JSON file:

vim server/database.json

Add the lines below to the file:

{
    "products": [
            "Shoes",
            "Books",
            "Pencils",
            "Pens",
            "School Uniform"
    ]
}

This file will act as the database for your REST API server. Now add the data you want to be served by the REST API.

Now edit the package.json file:

vim  package.json

Now add the server script to the file:

  "scripts": {
   "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "server": "json-server --watch ./server/database.json"
  },

Finally, start the REST API:

npm run server 

At this point, you can send HTTP requests to the server similarly o any other REST API server. The server is available at http://localhost:3000/

You can now have several endpoints for the REST API:

  • GET /products  for getting the products
  • GET /products/<id>  for getting a single product by id
  • POST /products  for creating a new product
  • PUT /products/<id>  for updating a product by id
  • PATCH /products/<id>  for partially updating a product by id
  • DELETE /products/<id>  for deleting a product by id

For example:

curl  http://localhost:3000/products

Sample Output:

Verdict

That marks the end of this guide on how to manage Angular JS Projects using Angular CLI. You can now use the Angular CLI to easily develop, scaffold, and maintain your Angular applications.

See more:

Cart

Your Cart is Empty

Back To Shop