Front-end Development – Angular and Bootstrap
Table of Contents
Introduction
Angular is a front-end framework and development platform that design to build single-page applications.
Angular application is written in Typescript, and integrated with an HTML template to create a dynamic design for a single-page web application.
For Angular architecture and basic concepts, refer to this link: https://angular.io/guide/architecture
AngularJS vs Angular
The older version which is known as AngularJs is a JavaScript library where can be added through an HTML <script>
tag. On the other hand, the latest versions which are Angular 2 and above are TypeScript-based web development frameworks. In other words, The AngularJS is totally different with Angular. The angular latest version is completely rewritten and done a lot of changes compared to AngularJs or Angular 1.
In this tutorial, we are going to use the Angular latest version (10.1.0). Refer to the next section to install and download the latest version.
What you need
- Before we dive into the actual tutorial, you should set up your local environment and workspace. To set up the environment and install angular go to the angular’s official site and follow the steps: Angular: Setup Local Environment
- Make sure you have essentials knowledge of web development: HTML, CSS, and Javascript Tutorial
- Ensure you have also a bit of knowledge of bootstrap: Bootstrap 4 Tutorial
- This tutorial requires back-end application, however, to keep it simple, we are going to add a fake back-end APIs. And it will take just 5 mins to do the setup, and it doesn’t require any coding.
Back-end Setup
In this section, we are going to set up the back-end application with zero codings. In that case, we are going to use a JSON Server to create a fake REST API that will pretend as a back-end application.
JSON Server is designed for front-end developers who want a quick back-end application for prototyping and mocking. You can visit the source(typicode) directly to GitHub: https://github.com/typicode/json-server
Install JSON Server using npm command line client:
npm install -g json-server
Once installed, create new file product.json, then copy-paste the json data below:
{
"products": [
{
"id": 1,
"productName": "Beauty Product",
"productDescription": "Lorem ipsum dolor sit amet, et sea cibo sadipscing, ei quo quot mediocrem qualisque, ad mel laudem volumus fabellas.",
"productPrice": 343.09
}
]
}
The Json data above will be served as initial data of our JSON server or REST API.
After you created a json file, you can now run the JSON Server by executing the command below:
json-server --watch product.json
When you go to http://localhost:3000/products, you will see the output below:
[
{
"id": 1,
"productName": "Beauty Product",
"productDescription": "Lorem ipsum dolor sit amet, et sea cibo sadipscing, ei quo quot mediocrem qualisque, ad mel laudem volumus fabellas.",
"productPrice": 343.09
}
]
And also when you use the other requests, like POST, PUT, PATCH
or DELETE
requests to change the data. Therefore, the changes will be automatically and safely saved to product.json
file using lowdb.
Here are the other HTTP requests, you can try them using HTTP request client like postman and curl:
- POST: http://localhost:3000/products
- PUT: http://localhost:3000/products/1
- DELETE: http://localhost:3000/products/1
In the next section, we are going to implement those requests in the front-end application
Application walk-through
In this tutorial, we will learn how to Create a Front-end Application with Angular and Bootstrap.
The application is base on the online shopping app, which will do the basic operations for products like Create-Read-Update-Delete(CRUD) operations.
See the video below for the front-end application demo:
Start creating project
Once you have already setup the environment, you can now use Angular CLI to create a project.
In order to create a new project with Angular CLI, copy-paste the script below and execute it using cmd
:
ng new shopping-app-angular
Enter y
when Angular CLI ask you about Angular routing.
And also, for the final step, choose SCSS
for the stylesheet format of our application.
Once the installation for the packages is done, open the project using editor or IDE. And I recommend VS Code as editor.
In order to run the application, copy-paste the script below and execute it in cmd:
cd shopping-app-angular
ng serve --open
Sometimes it took time to compile, but once it is done, the application will automatically open a new browser tab. if the application does not open a new tab, go to this default link http://localhost:4200/ for the application home page.
Download and install tools
Our next stuff is to install other libraries or tools of our project, including bootstrap, font-awesome, jquery, etc..
First thing is to download bootstrap libraries using cmd, cd to your project folder then copy-paste the script below to install the bootstrap:
npm install --save bootstrap
An alternative way is through TERMINAL in VS Code, click the Terminal tab, then select New Terminal. And then copy-paste the script above, Once the new tab open for the terminal:
Next is JQuery, though we will not use it, it still required when we use bootstrap libraries:
npm install --save jquery
And also font-awesome for icons of our application:
npm install font-awesome --save
Define tools in the configuration
Once you have installed the tools above, our next step is to define those tools in angular.json
file.
The angular.json
is located at the root level of the project or workspace, it is used to define or modify the default configuration.
Inside of “projects” -> “shopping-app-angular” -> “architect” -> “build” add the following properties below:
"styles": [
"src/styles.scss",
{
"input": "node_modules/bootstrap/dist/css/bootstrap.min.css"
},
{
"input": "node_modules/font-awesome/css/font-awesome.css"
}
],
"scripts": [
{
"input": "node_modules/jquery/dist/jquery.slim.min.js"
},
{
"input": "node_modules/bootstrap/dist/js/bootstrap.min.js"
}
]
The defined properties should be look like this:
Modify the default design
If you go to the http://localhost:4200/, you will see the default design is the same as below which is generated during the angular app creation:
First, we are going to remove everything in app.component.html.
And then copy and paste the code below to align with the design on the demo section:
<div class="row p-2 border-bottom">
<div class="col-auto p-0">
<img src="https://secureservercdn.net/198.71.233.129/u3a.0b4.myftpupload.com/wp-content/uploads/2020/08/lionLogi4.png" alt="Avatar" style="max-width:100px">
</div>
<div class="col-auto p-0">
<h4 class="text-secondary"><b>LGeraTech</b></h4>
<p class="text-black-50">Online Shopping Application</p>
</div>
</div>
<router-outlet></router-outlet>
Component
For the quick review, every module in angular apps contains classes, and each class can be used as a component, service, or module. And the only way to identify the use of the class is by defining the decorator with its properties.
Find out more about basic concepts of angular: https://angular.io/guide/architecture
The component has @Component
decorator which uses to tells angular what to do for the class of component.
The app.component.ts
is decorated by @Component
and defines the properties for selector
, templateUrl
and styleUrls
. These properties are used to integrate the HTML template to the typescript code. So we can render data or object to the HTML for the view and design purpose.
We’ve done the modification in the app.component.html
the file above, now our next is modify app.component.ts
or the typescript file.
Change the title variable from default value to:
title = 'Online Shopping Application';
Then change the <p> tag value in app.component.html
from static to:
...
<h4 class="text-secondary"><b>LGeraTech</b></h4>
<p class="text-black-50">{{title}}</p>
...
Therefore, the result is the same as the first modification, we just changed the title, so you can see how it looks like to render data from the typescript to HTML.
The use <router-outlet>
The <router-outlet>
tag in app.component.html
is used to load different components or views dynamically based on the current URL path or route state which enables a single-page web application structure.
And for the next section, in order to see how it works, we are going to use this feature.
Create Component for Product List
Before we get into component creation, we should add a model and service for the product data.
Model creation
Create product-model.ts
file and place it in app
folder, once created, copy-paste the code below:
export interface ProductModel {
id: number;
productName: string;
productDescription: string;
productPrice: string;
}
Add service
Create product.service.ts
file and place it in app
folder or you can create using command by executing this script:
ng generate service product
Once created, copy-paste the code below:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ProductModel } from './product-model';
@Injectable({
providedIn: 'root'
})
export class ProductService {
baseURL: string = 'http://localhost:3000';
headerOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
constructor(
private http: HttpClient
) { }
getProductList(): Observable<ProductModel[]>{
return this.http.get<ProductModel[]>(`${this.baseURL}/products`);
}
saveProduct(product: ProductModel): Observable<any>{
return this.http.post<any>(`${this.baseURL}/products`, product, this.headerOptions);
}
updateProduct(id, product: ProductModel): Observable<any>{
return this.http.put<any>(`${this.baseURL}/products/${id}`, product, this.headerOptions);
}
deleteProduct(id): Observable<any>{
return this.http.delete<any>(`${this.baseURL}/products/${id}`);
}
getProduct(id): Observable<ProductModel>{
return this.http.get<ProductModel>(`${this.baseURL}/products/${id}`);
}
}
The @Injectable
decorator enables dependency injection function, therefore, this class is injectable to other classes or components.
Dependency Injection is a design pattern that use to inject dependencies to a dependent class or object. And it uses run time environment to inject objects, rather than defining dependencies inside of it. On the words, dependency injection works through the backbone of the application to collect and inject dependencies.
You can find one of the examples of Dependency Injection via this link: http://lgeratech.com/2020/05/spring-framework-ioc-inversion-of-control/
And the baseURL
variable defines the base URL of our back-end APIs which we already set up on the back-end setup section
For the methods defined, they are used for HTTP requests, including for GET, POST, PUT and DELETE requests.
To ensure that the HTTP requests will work properly, we should add HttpClientModule
in app.module.ts
file:
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Generate Component
Generate component using cmd and by executing the script below. And once done it, a product-list folder will be generated:
ng generate component product-list
Install ToastrService
before we modify the component, we must add ToastrService
for a pop-up message so we can identify later on if the product is successful after executing any operations.
Go to the project folder through cmd or terminal, and execute the scripts below to install the toastr and animations:
npm install ngx-toastr --save
npm install @angular/animations --save
Once the installation is done, go to angular.json
and add the JSON
property below in the styles section as we did in the previous section :
{
"input": "node_modules/ngx-toastr/toastr.css"
}
For the final step, we must import the modules which are BrowserAnimationsModule
and ToastrModule
for toastr
in app.module.ts file:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
...
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
ToastrModule.forRoot(),
],
...
Product List Component Modification
Next is modifying the product list component, open the product-list.component.ts, and copy-paste the code below:
import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/product.service'
import { ProductModel } from '../product-model';
import { _ } from 'lodash';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.scss']
})
export class ProductListComponent implements OnInit {
productList: ProductModel[];
constructor(
private productService: ProductService,
private toastr: ToastrService
) { }
ngOnInit() {
this.loadProductList();
}
loadProductList(){
this.productService.getProductList().subscribe(res => this.productList=res)
}
deleteProduct(id){
this.productService.deleteProduct(id).subscribe(res =>{
this.toastr.success('Success', 'Delete Result');
this.loadProductList();
},error => {
this.toastr.error('deleteProduct error', 'Save Result');
});
}
}
And copy-paste the code below for product-list.component.html
:
<div class="row pl-2 pr-2 justify-content-start">
<div class="col-sm-3" *ngFor="let product of productList">
<div class='card m-2'>
<img class='card-img-top' [src]="'././assets/images/noImage.png'">
<div class='card-body text-left'>
<h5 class='card-title'>{{product.productName}}</h5>
<p class='card-text small'>{{product.productDescription}}</p>
<p class='card-text text-black-50 small'>{{product.productPrice}}</p>
</div>
<div class='card-footer text-center'>
<div class='row'>
<div class='col-6 p-0'>
<a class='text-black-50 btn btn-link btn-sm' [routerLink]="['/product-form', product.id]"><i class="fa fa-edit"></i> Edit</a>
</div>
<div class='col-6 p-0'>
<span class='text-black-50 btn btn-link btn-sm' (click)="deleteProduct(product.id)"><i class="fa fa-trash"></i> Delete</span>
</div>
</div>
</div>
</div>
</div>
</div>
Now we have finished the modification, the question is, how we’re going to view the component, the answer is via router module. Earlier in the previous section, we discussed <router-outlet>
tag in app.compoment.html
which use to change the page view dynamically.
To define a router view for product-list component, open the app-routing.module.ts file, then copy-paste the code below and add it inside of the routes
array:
const routes: Routes = [
{ path: 'product-list', component: ProductListComponent }
];
If you restart the application in go to http://localhost:4200, you will notice that there is existence of product list component.
However, when we access the path we defined in routes array http://localhost:4200/product-list, the product list component will be displayed:
Conclusion
Congratulation! We have done the front-end development using angular and bootstraps.
Go to the GitHub repository of this tutorial