How to build a real world application using Angular 9.

I will show you how to create a simple stock application in Angular 9 utilizing observables, services, models, components and many more.

In this article I will show you how to create a new Angular 9 project. Additionally I will walk you step-by-step and show you how to do the following:

  1. Use a styling library and reference it globally in your application
  2. Create a header which can be used across your entire application
  3. Create child component and utilize the @Input() decorator to pass information to it
  4. Usage of click event in Angular
  5. Usage of dependency injection
  6. Usage of models in Angular
  7. Two way data bind

Run the following command in VScode IDE to create an empty angular project:
> ng new my-stocks

We will use the bootstrap library for styling our application. To install bootstrap in our application go to the terminal in VScode and run the following command:
> npm install --save bootstrap

The command above will tell npm to download bootstrap and save it to the package.json file as well.

Once the bootstrap package has been successfully downloaded, we need to reference the css file globally in our project so that it can be available to us without needing to import it in every component.

To reference bootstrap you must do the following:

  1. In the EXPLORER pane in VScode locate the “angular.json” file
  2. In the “angular.json” file find the “styles” property which is an array and add the following path to it:
    ./node_modules/bootstrap/dist/css/bootstrap.min.css
    This is the path to the bootstrap minified cascade style sheet.

We need to create a header component. This component will be used as a top section on our application and will contain information such as the navigation bar.

In VScode terminal run the following command:
> ng generate component header

The command above will generate a new folder called header and inside it the following files will be created:

  • header.component.css
  • header.component.html
  • header.component.spec.ts
  • header.component.ts

Now open the “header.component.html” and let us modify its content. We need to add a navigation bar with a title and a single link called Home that will not point to anything at this moment. We will treat it as a placeholder.

<nav class="navbar navbar-expand-lg navbar-light bg-light">
My Stocks App |
<button class="navbar-toggler" type="button"
data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<div class="navbar-nav">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link">Home</a>
</li>
</ul>
</div>
</div>
</nav>

Here is a screen shot of how the header.component.html file looks so far:

To make this header display in our main application we need to reference it in the app.component.html.

  1. Open app.component.html
  2. Remove all of the html from it and replace it with the following html and save the file.
<app-header></app-header><div class="container">
<h3>Home</h3>
<hr>
</div>

At this point we have created a simple header file that we can reference on any component. In the header file we have added a navigation bar with a dummy link that we have named “Home”. Additionally, this header file has been referenced in our app.component.html.

Let’s compile our application to see how it looks using the following command in the VScode terminal:
> ng server -o

Our application should look like the following:

Alright, let us get going! We will need to display a list of the stocks that currently exist in our portfolio. Let us define our stock portfolio by creating an array of objects containing the name and symbol of each stock.

Open the app.component.ts file and add the following code:

stocks = [ 
{ symbol: 'TSLA', name: 'Tesla, Inc.'},
{ symbol: 'MSFT', name: 'Microsoft Corporation'},
{ symbol: 'SPCE', name: 'Virgin Galactic'},
{ symbol: 'CVS', name: 'CVS Pharmacy'},
];

We will use the items in the array to display them on the screen and make each item clickable. Clicking on each item (symbol) will cause the application to show a child component which will display information pertaining to the symbol selected (The clickable part and child component will be covered in the next section).

To display the list of stocks on the screen open the app.component.html and paste the following code:

<div *ngFor="let stock of stocks">
<div class="stock-div">
<span class="symbol">{{ stock.symbol }}</span>
<span class="company-name">({{ stock.name }})</span>
</div>
</div>

You will notice that I used *ngFor, this is the directive that is provided by Angular which allows us to loop through the array provided in the statment.

Next open the app.component.css and add the following CSS styling for the app component:

.stock-div{
display: block;
}
.stock-div .symbol{
font-weight: bold;
font-size: 14px;
cursor: pointer;
color: #0000fc;
}
.stock-div .symbol:hover{
text-decoration: underline;
}

.stock-div .company-name{
font-size: 13px;
padding-left: 5px;
}

Let us test the code to see how things are looking thus far. Compile the code and run it in the browser. Your application should look like this:

Now we will need to add a click event for each stock. This click event will make a child component “ticker-info” to appear on the side. The child component will display information such as the current value, the exchange name that the stock is being traded on, the volume and some other information (Child component will be covered in the next section).

Open the app.component.css one more time and let us modify the styles. We will need to make some changes to the css in order to account for the child component that we will work on next.

Here is the updated version of the app.component.css:

.stocks-div {
float: left;
width: 30%;
}
.stocks-div .stock-div{
display: block;
}
.stocks-div .stock-div .symbol{
font-weight: bold;
font-size: 14px;
cursor: pointer;
color: #0000fc;
}
.stocks-div .stock-div .symbol:hover{
text-decoration: underline;
}
.stocks-div .stock-div .company-name{
font-size: 13px;
padding-left: 5px;
}
.ticker-info-div{
float: left;
width: 70%;
}

Next, let us modify the code on the app.component.ts. We need to create a variable that will hold the stock name once it gets selected. Additionally, we will need to create a function that will drive the click event.

Here is the code that you will need to add:

selectedStock: string;ngOnInit(){
this.selectedStock = '';
}
stockClicked(symbol){
this.selectedStock = symbol;
}

Next, open the app.component.html and let us modify the html as such:

<div class="stocks-div">
<div *ngFor="let stock of stocks">
<div class="stock-div" (click)="stockClicked(stock.symbol)">
<span class="symbol">{{ stock.symbol }}</span>
<span class="company-name">({{ stock.name }})</span
</div>
</div>
</div>
<div class="ticker-info-div">
<app-ticker-info
[ticker]="selectedStock"
*ngIf="selectedStock !== ''"></app-ticker-info>
</div>

If you save and compile your code, you will get an error and that is because of the child component that we have not yet created:

<app-ticker-info 
[ticker]="selectedStock"
*ngIf="selectedStock !== ''"></app-ticker-info>

In the next section we will create the child component.

Now we need to create a component which will display ticker information such as the name, current value, which exchange it is being traded on and so on.

In VSCode terminal type the following command to create the component:
> ng generate component ticker-info

This command will generate the component under the app folder structure.

This component will require the following information to be passed in to it from the parent component:

  • Ticker

In the ticker-info.component.ts file lets add the following variable with the @Input() decorator:

@Input() ticker: string;

At this point, the code in the ticker-info.component.ts should look like this:

Now, open the ticker-info.component.html file and let’s replace its content with the following HTML:

<h4>{{ tickerName }}</h4>

At this point, the code should compile successfully. Once compiled, run the code in the browser and click on a specific stock. You will notice that the name of the symbol will appear to the right of the portfolio list.

This is an indication that the child component is working as expected.

As mentioned previously, the child component will retrieve information about the stock selected and display it to the screen. To obtain information pertaining to the stock we will need to leverage the Yahoo Finance API for real time stock information.

In the next section I will walk you through how to create a service which will implement a method that will communicate with the Yahoo Finance API via http request.

We need to create a service that will be injected in the child component. This service will contain a function that will communicate with the Yahoo Finance API via a GET request to retrieve information.

To create the service run the following command in VScode terminal:

ng generate service ../shared/data

This command will generate a new service called data under the src>shared folder structure. You will notice that the command has also generated data.service.spec.ts file which is used for unit testing and we can ignore it for now. We will not be talking about unit testing in this article. I can potentially write a separate article about it in the future.

Next, open the data.service.ts file and add the following code:

private api = 'https://query1.finance.yahoo.com/v8/finance/chart/{0}?region=US&lang=en-US&includePrePost=false&interval=2m&range=1d&.tsrc=finance';constructor(private httpClient: HttpClient) { }public getStockInformation(ticker){
let api = this.api.replace('{0}', ticker);
return this.httpClient.get(api);
}

Make sure to include the following import:

import { HttpClient } from '@angular/common/http';

In the constructor of the class make sure to also inject the HttpClient as follows:

constructor(private httpClient: HttpClient) { }

In the solution, locate the app.modules.ts and add the following import statement at the top of the class:

import { HttpClientModule } from '@angular/common/http';

We also need to add an additional import “ HttpClientModule” to the imports object in the @NgModule decorator.

Let us create a model which will be used to hold the information returned from the Yahoo Finance service. This method will be used in the child component. The object returned by the service will be directly mapped into the model.

Create a new folder under the screen folder structure and name it “models”. Inside the folder create a new stock-info.ts file and name it stockInfo.

Inside the stock-info.ts class add the following class properties:

export class StockInfo {
public displayName: string;
public currentPrice: number;
public changeinPoints: number;
public isPositive: boolean;
public currency: string;
public percentageGains: number;
public exchangeName: string;
public previousClose: number;
public closePrice: number;
public openPrice: number;
public highPrice: number;
public lowPrice: number;
public volume: number;
}

Now that the service method has been implemented and the model is created we will need to call it from the child component to retrieve the stock information.

Open the ticker-info.component.ts and add the following import statements at the top of the file:

import { Subscription, timer } from 'rxjs';
import { DataService } from 'src/shared/data.service';
import { switchMap } from 'rxjs/operators';

Next, we need to inject the service in our child component and to do that let us make the following change to the constructor:

constructor(private dataService: DataService) { }

At this point, the data service has been injected into our child component and any methods belonging to the service are available to us. In our case the service only contains one method.

Now let’s copy the code below and paste it into our child component ticker-info.component.ts

stockInfo: StockInfo
subscription: Subscription;
stockInformation: any;
ngOnInit(): void {
this.stockInfo = null;
if(this.ticker && this.ticker !== ''){
this.subscription = timer(0, 500)
.pipe(switchMap(() =>
this.dataService.getStockInformation(this.ticker)))
.subscribe(result => {
let response: any;
response = result;
if(response.chart && response.chart.result &&
response.chart.result.length > 0){
this.stockInformation =
response.chart.result[0].meta;

let stockIndicators =
response.chart.result[0]
.indicators.quote[0];
this.stockInfo = new StockInfo();
this.stockInfo.displayName =
this.stockInformation.symbol;
this.stockInfo.currentPrice =
this.stockInformation
.regularMarketPrice;
this.stockInfo.changeinPoints =
this.stockInformation
.regularMarketPrice -
this.stockInformation
.chartPreviousClose;
this.stockInfo.isPositive =
(this.stockInformation
.regularMarketPrice -
this.stockInformation
.chartPreviousClose)
> 0 ? true : false;
this.stockInfo.currency =
this.stockInformation.currency;
this.stockInfo.percentageGains =
((this.stockInformation
.regularMarketPrice -
this.stockInformation
.chartPreviousClose) /
this.stockInformation
.regularMarketPrice) * 100;
this.stockInfo.exchangeName =
this.stockInformation.exchangeName;
this.stockInfo.previousClose =
this.stockInformation.previousClose;
this.stockInfo.closePrice =
stockIndicators.close[0];
this.stockInfo.openPrice = stockIndicators.open[0]; this.stockInfo.highPrice = stockIndicators.high[0]; this.stockInfo.lowPrice = stockIndicators.low[0]; this.stockInfo.volume = stockIndicators.volume[0]; }
});
}
}
ngOnDestroy(){
this.stockInformation = null;
this.subscription.unsubscribe();
}

Inside the ngOnInit lifecycle hook you will notice that we subscribed to the “getStockInformation” service method which will fetch a specific stock information from the Yahoo Finance API. Additionally, you will notice the timer() function, this will tell the code to execute the “getStockInformation” at 500ms interval.

Inside the arrow expression you will notice that the information that is being returned from the service call is being mapped to the model that we have instantiated.

Now let’s let us make the final changes to our ticker-info.component.html. We will need to add the HTML tags that will display the information pertaining to the stock.

Copy the code below inside the stock-info.component.html:

<div *ngIf="stockInfo">
<h4>{{ stockInfo.displayName }}</h4>
<span class="exchange-name">
{{ stockInfo.exchangeName }} -
Currency in {{ stockInfo.currency }}
</span>
<div>
<span class="current-price">
{{ stockInfo.currentPrice }}</span>
<span class="current-points-gain"
[ngClass]="{'positive': stockInfo.isPositive,
'negative': !stockInfo.isPositive}">
{{ stockInfo.changeinPoints.toFixed(2)}}
</span>
<span class="current-gains"
[ngClass]="{'positive': stockInfo.isPositive,
'negative': !stockInfo.isPositive}">
({{ stockInfo.percentageGains.toFixed(2)}}%)
</span>
</div>
<hr>
<div>
<label class="info-label">Open Price:</label>
<span>{{ stockInfo.openPrice.toFixed(2) }}</span>
</div>
<div>
<label class="info-label">Close Price:</label>
<span>{{ stockInfo.closePrice.toFixed(2) }}</span>
</div>
<div>
<label class="info-label">High Price:</label>
<span>{{ stockInfo.highPrice.toFixed(2) }}</span>
</div>
<div>
<label class="info-label">Low Price:</label>
<span>{{ stockInfo.lowPrice.toFixed(2) }}</span>
</div>
<div>
<label class="info-label">Volume Price:</label>
<span>{{ stockInfo.volume| number }}</span>
</div>
</div>

Next, switch over to the stock-info.component.css and replace all the content inside the file with the following styles:

.exchange-namef
font-size: 13px;
font-weight: bold;
color: #555;
}
.current-price{
font-size: 20px;
font-weight: bold;
}
.current-points-gain{
padding-left: 10px;
}
.current-gains{
padding-left: 2px;
}
.positive{
color: #093;
}
.negative{
color: #ff333a;
}
.info-label{
font-weight: bold;
padding-right: 10px;
}

Alright, at this point we have finished the implementation of our application and it is time to view the final result. To see the application running we must fist compile the code.

Run this command in VScode terminal:

ng server -o

Once the application is done being compiled it will launch in a brownser. You will see the list of the stocks in our portfolio. If you click on a particular stock you will notice that on the right hand side information pertaining to the stock you click on will appear. If you chose another stock and click on it the information will change immediately.

In this article I was able to show you how to create a new Angular 9 project. Additionally, I walked you step-by-step and show you how to do the following:

  1. Use a styling library and reference it globally in your application
  2. Create a header which can be used across your entire application
  3. Create child component and utilize the @Input() decorator to pass information to it
  4. Usage of click event in Angular
  5. Usage of dependency injection
  6. Usage of models in Angular
  7. Two way data bind

I hope this article was beneficial to you and please leave a comment below if you have any questions.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store