Watts Kendall

Watts Kendall

1548141242

Create a cryptocurrency dashboard with Angular

In this tutorial , we will be creating a cryptocurrency dashboard using Angular 4 and Angular IDE. Cryptocurrency is a digital asset designed to work as a medium of exchange using cryptography to secure the transactions and to control the creation of additional units of the currency. Bitcoin is the most popular digital currency, however there are numerous cryptocurrencies in existence.

On our dashboard, we will display the price, percentage change in 24 hour price, and percentage change in 7 day price of selected cryptocurrencies.

What You will Learn

In this article you will learn about Angular application development using Angular IDE. You will also learn how to use the Subject class from RxJS, a ReactiveX library for javascript.

Prerequisites

In order to follow along with this tutorial, please ensure you have installed Angular IDE.

UI Design

Below is a picture of how the cryptocurrency dashboard will look like on mobile.

Step 1 — Create new Angular project

Open Angular IDE, click File in the top menu, then select, New then click.Angular Project

In the new Angular project wizard, type crypto-dashboard as the project name, select node version 6.11.4, and npm version 3.10.10. Then click the finish button.

Angular IDE will take a few minutes to set up the project, you can see the activities output in Terminal+. Once completed we see an output like in the image below

Step 2 — Create application components

Taking a look at our UI design, we can identify two visible components, the search-filter box, and the list card. There is also an invisible component which is the list itself. The components are highlighted in the picture below:

Now, let’s create the components. In the file explorer view, right click on crypto-dashboard, select new, and click.Component

In the New Angular CLI dialog, enter search-filter as element name, and click the finish button. See image below for reference:

Repeat the steps to create the list-card, and list component. Also create a dashboard component, so we use it to organize our components. Your directory structure, under the src/app folder should be as in the image below:

Create AppService

In this tutorial, we will be using just one Angular Service, named AppService. In Angular, a Service is a broad category encompassing any value, function, or feature that your application needs.

In the file explorer view, right click on crypto-dashboard, select new, and click Service. In the new Angular CLI Service wizard, enter App a the element name, and click finish.

Add Bootstrap CSS and Font Awesome

Let us add bootstrap css and font awesome to our project by updating the contents of src/index.html , add the code snippet below in the head section of the html document

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css">
<link href='//fonts.googleapis.com/css?family=Open+Sans:400,700'
rel='stylesheet' type='text/css'>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.css" />

Install angular-2-dropdown-multiselect

AngularX Dropdown Multiselect for Bootstrap CSS is used to create customizable dropdown multiselect in AngularX, TypeScript with bootstrap css. We will be needing multiselect in this project, so let’s install it by typing the command below in Terminal+ and hitting enter

npm install --save angular-2-dropdown-multiselect

In order to make the multiselect component available in our application, we need to update src/app/app.module.ts as follows:

...
import {MultiselectDropdownModule} from 'angular-2-dropdown-multiselect';

@NgModule({

imports: [

MultiselectDropdownModule,
],

Here is a screenshot of how the multi-select plugin will appear in our final result.

The API

We will be using the api provided by coinmarketcap.com. Using the sample data returned, let us create a type script shape file named coin.ts with the following content

export class Coin {
id: string;
name: string;
symbol: string;
rank: string;
price_usd: string;
price_btc: string;
‘24h_volume_usd’: string;
market_cap_usd: string;
available_supply: string;
total_supply: string;
percent_change_1h: string;
percent_change_24h: string;
percent_change_7d: string;
last_updated: string;
}

App Service

AppService is a general purpose class we will use to fetch data from the api, and pass that data on to components. We also use AppService to filter the data to display based on the options selected in the app. We could split this service into multiple services so as to abide by the single responsibility principle.

The Subject class from RxJs is very important in this code section and it’s important to touch on what they are. Firstly let us talk about RxJs, it is a reactive programming framework for Javascript. Core to understanding how to use RxJs is having a mental model of the Observer Pattern. The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

First we import {Injectable} from @angular/core, {Subject} from rxjs/Subject, {HttpClient, HttpParams} from @angular/common/http . Next we import the coin shape Coin from ./coin, and we create a constant APIBASEURL to hold the base url of the api.

Now we export class AppService, making sure we decorate it using @Injectable(), then we define three private variables allCoins: Coin[], filteredCoins: Coin[], and filter: number[]. We also define four subjects

  • coinsSubject: Which notifies it’s observers of coin data fetched from the API
  • filteredCoinsSubject: Which notifies it’s observers the filtered collection of crypto currency data. So if in the multiselect filter, only two crypto coins are selected then, the most recent value emitted by subscribing to filteredCoinsSubject will be an array of length two.
  • apiSubject : notifies it’s observers with a string message based on api actions
  • fiatSubject :notifies it’s observers about the value of the selected fiat currency when it is updated.

The full code for AppService is below, explanations are in the comments

// Imports
import {Injectable} from ‘@angular/core’;
import {Subject} from ‘rxjs/Subject’;
import {HttpClient, HttpParams} from ‘@angular/common/http’;
// Import Coin Shape file
import {Coin} from ‘./coin’;
const API_BASE_URL = ‘https://api.coinmarketcap.com/v1/’;

@Injectable()
export class AppService {
private allCoins: Coin[]; // will hold unmodified data returned by the api
private filteredCoins: Coin[]; // will hold data filtered from this.allCoins
private filter: number[]; // will hold the array index of data contained in this.
allCoins that should not be filtered out

// A couple of RxJs Subjects very important for communicating across Angular Components
coinsSubject: Subject<Coin[]>;
filteredCoinsSubject: Subject<Coin[]>;
apiSubject: Subject;
fiatSubject: Subject;
constructor(private http: HttpClient) {
this.filter = [];
// we initialize our subjects
this.coinsSubject = new Subject();
this.filteredCoinsSubject = new Subject();
this.apiSubject = new Subject();
this.fiatSubject = new Subject();
}
// this method loads market cap data from the API
loadMarketCaps(fiat: string) {
this.fiatSubject.next(fiat);
const url = API_BASE_URL + ‘ticker/’;
let params = new HttpParams();
params = params.append(‘limit’, ‘25’);
if (fiat !== ‘usd’) {
// TODO: check if fiat is valid
params = params.append(‘convert’, fiat);
}
this.apiSubject.next(‘loading…’);
this.http
.get<Coin[]>(url, {params})
.subscribe(
data => {
this.allCoins = data; // store returned data
this.announceCoins(); // trigger announcements
this.filterMarketCaps();
}
);
}

filterMarketCaps() {
this.filteredCoins = [];
if (this.filter.length === 0) {
this.allCoins.forEach((coin) => this.filteredCoins.push(coin));
}
if (this.filter.length > 0) {
this.filter.forEach((i) => {
this.filteredCoins.push(this.allCoins[i]);
});
}
this.announceFilteredCoins();
}
announceCoins() {
this.coinsSubject.next(this.allCoins);
}
announceFilteredCoins() {
this.filteredCoinsSubject.next(this.filteredCoins);
}
updateFilter(filter: number[]) {
this.filter = [];
filter.forEach((elem) => {
this.filter.push(elem);
});
this.filterMarketCaps();
}
}

App Component

Update the content of src/app/app.component.html with the content below. We display the title in a h2 element, and we set the dashboard component as a child view. If our project needed a router, we would have set it up here in App component.

<div class=“container”>
<div class=“row”>
<div class=“col-sm-6 col-sm-offset-3”>
<h2 class=“text-center”>{{ title }}</h2>
<app-dashboard></app-dashboard>
</div>
</div>
</div>

Dashboard Component

The dashboard component will serve as a parent component for two components, the search component and the list component. Replace the contents of src/app/dashboard/dashboard.component.html with the code snippet below

<app-search-filter></app-search-filter>
<app-list></app-list>

Since the scope of the service instance is the parent component and its children, we will create an instance of AppService in the dashboard component which will be shared by the search-filter component and the list component. To do this we update src/app/dashboard/dashboard.component.ts by importing AppService, and adding AppSercieto the providers array which enables Angular’s Dependency Injector for AppService.

import {Component} from ‘@angular/core’;
// import AppService
import {AppService} from ‘…/app.service’;
@Component({
selector: ‘app-dashboard’,
templateUrl: ‘./dashboard.component.html’,
styleUrls: [‘./dashboard.component.css’],
providers: [AppService] // provider setup
})
export class DashboardComponent {}

SearchFilter Component

The search-filter component is made up of a form containing two elements.

The first is a select element for choosing a fiat currency used in displaying the current worth of each crypto currency. The selected currency will be stored in a model aptly named SelectedCurrency , an onChange event listener will notify the app service to load data from the api.

The second element is is a multiselect dropdown, that will enable us filter our choice of crypto currencies to display.

The code below goes in src/app/search-filter/search-filter.component.html

<div>
<form>
<div class=“form-group”>
<select id=“selectedCurrency” name=“selectedCurrency” [(ngModel)]=“selectedCurrency”
(change)=“selectCurrency($event.target.value)” class=“form-control”
id=“fiat”>
<option value=“”>Select fiat currency</option>
<option *ngFor=“let currency of currencies” value=“{{currency}}”>{{currency.toUpperCase()}}</option>
</select>
</div>
<div class=“form-group”>
<ss-multiselect-dropdown id=“cryptocurrencies”
name=“cryptocurrencies” [texts]=“myTexts” [settings]=“mySettings”
[options]=“cryptoCurrOptions” [(ngModel)]=“optionsModel”
(ngModelChange)=“filterChange($event)”></ss-multiselect-dropdown>
</div>
</form>
</div>

and the code below goes in src/app/search-filter/search-filter.component.ts

// Imports
import {Component, EventEmitter, Input, OnInit, Output} from ‘@angular/core’;
import {AppService} from ‘…/app.service’;
import {IMultiSelectOption, IMultiSelectSettings, IMultiSelectTexts} from ‘angular-2-dropdown-multiselect’;
@Component({
selector: ‘app-search-filter’,
templateUrl: ‘./search-filter.component.html’,
styleUrls: [‘./search-filter.component.css’],
providers: []
})
export class SearchFilterComponent implements OnInit {
currencies: string[];
cryptoCurrOptions: IMultiSelectOption[];
selectedCurrency: string;
optionsModel: number[];
// Settings configuration for the multiselect plugin
mySettings: IMultiSelectSettings = {
enableSearch: true,
checkedStyle: ‘fontawesome’,
buttonClasses: ‘btn btn-default btn-block’,
dynamicTitleMaxItems: 5,
displayAllSelectedText: true
};
// Text configuration for the multiselect plugin
myTexts: IMultiSelectTexts = {
checkAll: ‘Select all’,
uncheckAll: ‘Unselect all’,
checked: ‘item selected’,
checkedPlural: ‘items selected’,
searchPlaceholder: ‘Find’,
searchEmptyResult: ‘Nothing found…’,
searchNoRenderText: ‘Type in search box to see results…’,
defaultTitle: ‘Filter cryptos’,
allSelected: ‘All selected’,
};
constructor(private appService: AppService) {
this.currencies = [‘usd’, ‘eur’]; // fiat currency options
this.selectedCurrency = ‘’; // model to store selected fiat
// array to hold names of cryptos to be used in filtering
this.cryptoCurrOptions = [];
// coinsSubject is a RxJs subject in our service that will notify us when the api has gotten data about crypto coins
this.appService.coinsSubject.subscribe({
next: (v) => this.updateCryptoOptions(v),
});
}
ngOnInit() {
}
selectCurrency(newValue) {
this.appService.loadMarketCaps(newValue);
}
filterChange(newValue) {
// BUG method should not be triggered by filter select
this.appService.updateFilter(newValue);
}
// This method creates an array of valid options for the multiselect plugin from an array of crypto coins
updateCryptoOptions(coins) {
this.cryptoCurrOptions = [];
coins.forEach((coin, index) => {
this.cryptoCurrOptions.push({
id: index,
name: coin.id.charAt(0).toUpperCase() + coin.id.slice(1)
});
});
}
}

List Component

This component manages the display of a list of cards. One for each crypto coin data returned from the api. The coins model is an array of the data to rendered by each coin. Let us update the contents of src/app/list/list.component.html

<div class=“list-cards pb-4”>
<app-list-card *ngFor=“let coin of coins” [coin]=“coin” [fiat]=“fiat”></app-list-card>
</div>
<div *ngIf=“!coins”>
{{noDataMsg || ‘Nothing to display’}}
</div>

The content of src/app/list/list.component.css is

.list-cards {
display: flex;
flex-direction: column;
align-items: center;
}

In src/app/list/list.component.ts , we subscribe to three RxJs subjects in our Service.

  • filteredCoinsSubject: Which sends updates on the filtered collection of crypto currency data. So if in the multiselect filter, only two crypto coins are selected then, the most recent value emitted by subscribing to filteredCoinsSubject will be an array of length two.
  • apiSubject : emits a string message based on api actions
  • fiatSubject : emits the value of the selected fiat currency when it is updated.
import {Component, Input, OnInit} from ‘@angular/core’;
import {AppService} from ‘…/app.service’;
import {Coin} from ‘…/coin’;
@Component({
selector: ‘app-list’,
templateUrl: ‘./list.component.html’,
styleUrls: [‘./list.component.css’]
})
export class ListComponent implements OnInit {
coins: Coin[];
noDataMsg: string;
fiat: string;
constructor(private appService: AppService) {
this.noDataMsg = ‘Select fiat currency to get started’;
this.appService.filteredCoinsSubject.subscribe({
next: (v) => this.updateCoins(v),
});
this.appService.apiSubject.subscribe({
next: (msg) => this.noDataMsg = msg,
});
this.appService.fiatSubject.subscribe({
next: (newValue) => this.fiat = newValue,
});
}
updateCoins(coins: Coin[]) {
this.coins = [];
coins.forEach((coin) => this.coins.push(coin));
}
ngOnInit() {
}
}

ListCard Component

The list-card component, is basically to display the market cap summary of a single cryptocurrency. The content of src/app/list-card/list-card.component.html is below

<div class=“card text-center mt-4”>
<div class=“card-body”>
<h2 class=“card-title”>{{ coin.id }}</h2>
<h4 class=“mb-0 pb-1”>{{fiat.toUpperCase()}} {{ coin[‘price_’+fiat] }}</h4>
</div>
<ul class=“list-group list-group-flush”>
<li class=“list-group-item”>24 hours: <span [class]="coin.percent_change_24h.charAt(0)===‘-’ ? ‘red’ : ‘green’ ">{{ coin.percent_change_24h
}}</span></li>
<li class=“list-group-item”>7 days: <span [class]="coin.percent_change_24h.charAt(0)===‘-’ ? ‘red’ : ‘green’ ">{{ coin.percent_change_7d }}</span></li>
</ul>
</div>

and src/app/list-card/list-card.component.ts

import {Component, OnInit, Input} from ‘@angular/core’;
@Component({
selector: ‘app-list-card’,
templateUrl: ‘./list-card.component.html’,
styleUrls: [‘./list-card.component.css’]
})
export class ListCardComponent {
@Input() coin;
@Input() fiat;
}

Run application

Run the application from the server tab of Angular IDE.

Conclusion

I hope you learnt a few things about Angular and Angular IDE. Thanks!


#javascript #angular.js #angular #blockchain #bitcoin #cryptocurrency

What is GEEK

Buddha Community

Create a cryptocurrency dashboard with Angular
Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Watts Kendall

Watts Kendall

1548141242

Create a cryptocurrency dashboard with Angular

In this tutorial , we will be creating a cryptocurrency dashboard using Angular 4 and Angular IDE. Cryptocurrency is a digital asset designed to work as a medium of exchange using cryptography to secure the transactions and to control the creation of additional units of the currency. Bitcoin is the most popular digital currency, however there are numerous cryptocurrencies in existence.

On our dashboard, we will display the price, percentage change in 24 hour price, and percentage change in 7 day price of selected cryptocurrencies.

What You will Learn

In this article you will learn about Angular application development using Angular IDE. You will also learn how to use the Subject class from RxJS, a ReactiveX library for javascript.

Prerequisites

In order to follow along with this tutorial, please ensure you have installed Angular IDE.

UI Design

Below is a picture of how the cryptocurrency dashboard will look like on mobile.

Step 1 — Create new Angular project

Open Angular IDE, click File in the top menu, then select, New then click.Angular Project

In the new Angular project wizard, type crypto-dashboard as the project name, select node version 6.11.4, and npm version 3.10.10. Then click the finish button.

Angular IDE will take a few minutes to set up the project, you can see the activities output in Terminal+. Once completed we see an output like in the image below

Step 2 — Create application components

Taking a look at our UI design, we can identify two visible components, the search-filter box, and the list card. There is also an invisible component which is the list itself. The components are highlighted in the picture below:

Now, let’s create the components. In the file explorer view, right click on crypto-dashboard, select new, and click.Component

In the New Angular CLI dialog, enter search-filter as element name, and click the finish button. See image below for reference:

Repeat the steps to create the list-card, and list component. Also create a dashboard component, so we use it to organize our components. Your directory structure, under the src/app folder should be as in the image below:

Create AppService

In this tutorial, we will be using just one Angular Service, named AppService. In Angular, a Service is a broad category encompassing any value, function, or feature that your application needs.

In the file explorer view, right click on crypto-dashboard, select new, and click Service. In the new Angular CLI Service wizard, enter App a the element name, and click finish.

Add Bootstrap CSS and Font Awesome

Let us add bootstrap css and font awesome to our project by updating the contents of src/index.html , add the code snippet below in the head section of the html document

<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css">
<link href='//fonts.googleapis.com/css?family=Open+Sans:400,700'
rel='stylesheet' type='text/css'>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.css" />

Install angular-2-dropdown-multiselect

AngularX Dropdown Multiselect for Bootstrap CSS is used to create customizable dropdown multiselect in AngularX, TypeScript with bootstrap css. We will be needing multiselect in this project, so let’s install it by typing the command below in Terminal+ and hitting enter

npm install --save angular-2-dropdown-multiselect

In order to make the multiselect component available in our application, we need to update src/app/app.module.ts as follows:

...
import {MultiselectDropdownModule} from 'angular-2-dropdown-multiselect';

@NgModule({

imports: [

MultiselectDropdownModule,
],

Here is a screenshot of how the multi-select plugin will appear in our final result.

The API

We will be using the api provided by coinmarketcap.com. Using the sample data returned, let us create a type script shape file named coin.ts with the following content

export class Coin {
id: string;
name: string;
symbol: string;
rank: string;
price_usd: string;
price_btc: string;
‘24h_volume_usd’: string;
market_cap_usd: string;
available_supply: string;
total_supply: string;
percent_change_1h: string;
percent_change_24h: string;
percent_change_7d: string;
last_updated: string;
}

App Service

AppService is a general purpose class we will use to fetch data from the api, and pass that data on to components. We also use AppService to filter the data to display based on the options selected in the app. We could split this service into multiple services so as to abide by the single responsibility principle.

The Subject class from RxJs is very important in this code section and it’s important to touch on what they are. Firstly let us talk about RxJs, it is a reactive programming framework for Javascript. Core to understanding how to use RxJs is having a mental model of the Observer Pattern. The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

First we import {Injectable} from @angular/core, {Subject} from rxjs/Subject, {HttpClient, HttpParams} from @angular/common/http . Next we import the coin shape Coin from ./coin, and we create a constant APIBASEURL to hold the base url of the api.

Now we export class AppService, making sure we decorate it using @Injectable(), then we define three private variables allCoins: Coin[], filteredCoins: Coin[], and filter: number[]. We also define four subjects

  • coinsSubject: Which notifies it’s observers of coin data fetched from the API
  • filteredCoinsSubject: Which notifies it’s observers the filtered collection of crypto currency data. So if in the multiselect filter, only two crypto coins are selected then, the most recent value emitted by subscribing to filteredCoinsSubject will be an array of length two.
  • apiSubject : notifies it’s observers with a string message based on api actions
  • fiatSubject :notifies it’s observers about the value of the selected fiat currency when it is updated.

The full code for AppService is below, explanations are in the comments

// Imports
import {Injectable} from ‘@angular/core’;
import {Subject} from ‘rxjs/Subject’;
import {HttpClient, HttpParams} from ‘@angular/common/http’;
// Import Coin Shape file
import {Coin} from ‘./coin’;
const API_BASE_URL = ‘https://api.coinmarketcap.com/v1/’;

@Injectable()
export class AppService {
private allCoins: Coin[]; // will hold unmodified data returned by the api
private filteredCoins: Coin[]; // will hold data filtered from this.allCoins
private filter: number[]; // will hold the array index of data contained in this.
allCoins that should not be filtered out

// A couple of RxJs Subjects very important for communicating across Angular Components
coinsSubject: Subject<Coin[]>;
filteredCoinsSubject: Subject<Coin[]>;
apiSubject: Subject;
fiatSubject: Subject;
constructor(private http: HttpClient) {
this.filter = [];
// we initialize our subjects
this.coinsSubject = new Subject();
this.filteredCoinsSubject = new Subject();
this.apiSubject = new Subject();
this.fiatSubject = new Subject();
}
// this method loads market cap data from the API
loadMarketCaps(fiat: string) {
this.fiatSubject.next(fiat);
const url = API_BASE_URL + ‘ticker/’;
let params = new HttpParams();
params = params.append(‘limit’, ‘25’);
if (fiat !== ‘usd’) {
// TODO: check if fiat is valid
params = params.append(‘convert’, fiat);
}
this.apiSubject.next(‘loading…’);
this.http
.get<Coin[]>(url, {params})
.subscribe(
data => {
this.allCoins = data; // store returned data
this.announceCoins(); // trigger announcements
this.filterMarketCaps();
}
);
}

filterMarketCaps() {
this.filteredCoins = [];
if (this.filter.length === 0) {
this.allCoins.forEach((coin) => this.filteredCoins.push(coin));
}
if (this.filter.length > 0) {
this.filter.forEach((i) => {
this.filteredCoins.push(this.allCoins[i]);
});
}
this.announceFilteredCoins();
}
announceCoins() {
this.coinsSubject.next(this.allCoins);
}
announceFilteredCoins() {
this.filteredCoinsSubject.next(this.filteredCoins);
}
updateFilter(filter: number[]) {
this.filter = [];
filter.forEach((elem) => {
this.filter.push(elem);
});
this.filterMarketCaps();
}
}

App Component

Update the content of src/app/app.component.html with the content below. We display the title in a h2 element, and we set the dashboard component as a child view. If our project needed a router, we would have set it up here in App component.

<div class=“container”>
<div class=“row”>
<div class=“col-sm-6 col-sm-offset-3”>
<h2 class=“text-center”>{{ title }}</h2>
<app-dashboard></app-dashboard>
</div>
</div>
</div>

Dashboard Component

The dashboard component will serve as a parent component for two components, the search component and the list component. Replace the contents of src/app/dashboard/dashboard.component.html with the code snippet below

<app-search-filter></app-search-filter>
<app-list></app-list>

Since the scope of the service instance is the parent component and its children, we will create an instance of AppService in the dashboard component which will be shared by the search-filter component and the list component. To do this we update src/app/dashboard/dashboard.component.ts by importing AppService, and adding AppSercieto the providers array which enables Angular’s Dependency Injector for AppService.

import {Component} from ‘@angular/core’;
// import AppService
import {AppService} from ‘…/app.service’;
@Component({
selector: ‘app-dashboard’,
templateUrl: ‘./dashboard.component.html’,
styleUrls: [‘./dashboard.component.css’],
providers: [AppService] // provider setup
})
export class DashboardComponent {}

SearchFilter Component

The search-filter component is made up of a form containing two elements.

The first is a select element for choosing a fiat currency used in displaying the current worth of each crypto currency. The selected currency will be stored in a model aptly named SelectedCurrency , an onChange event listener will notify the app service to load data from the api.

The second element is is a multiselect dropdown, that will enable us filter our choice of crypto currencies to display.

The code below goes in src/app/search-filter/search-filter.component.html

<div>
<form>
<div class=“form-group”>
<select id=“selectedCurrency” name=“selectedCurrency” [(ngModel)]=“selectedCurrency”
(change)=“selectCurrency($event.target.value)” class=“form-control”
id=“fiat”>
<option value=“”>Select fiat currency</option>
<option *ngFor=“let currency of currencies” value=“{{currency}}”>{{currency.toUpperCase()}}</option>
</select>
</div>
<div class=“form-group”>
<ss-multiselect-dropdown id=“cryptocurrencies”
name=“cryptocurrencies” [texts]=“myTexts” [settings]=“mySettings”
[options]=“cryptoCurrOptions” [(ngModel)]=“optionsModel”
(ngModelChange)=“filterChange($event)”></ss-multiselect-dropdown>
</div>
</form>
</div>

and the code below goes in src/app/search-filter/search-filter.component.ts

// Imports
import {Component, EventEmitter, Input, OnInit, Output} from ‘@angular/core’;
import {AppService} from ‘…/app.service’;
import {IMultiSelectOption, IMultiSelectSettings, IMultiSelectTexts} from ‘angular-2-dropdown-multiselect’;
@Component({
selector: ‘app-search-filter’,
templateUrl: ‘./search-filter.component.html’,
styleUrls: [‘./search-filter.component.css’],
providers: []
})
export class SearchFilterComponent implements OnInit {
currencies: string[];
cryptoCurrOptions: IMultiSelectOption[];
selectedCurrency: string;
optionsModel: number[];
// Settings configuration for the multiselect plugin
mySettings: IMultiSelectSettings = {
enableSearch: true,
checkedStyle: ‘fontawesome’,
buttonClasses: ‘btn btn-default btn-block’,
dynamicTitleMaxItems: 5,
displayAllSelectedText: true
};
// Text configuration for the multiselect plugin
myTexts: IMultiSelectTexts = {
checkAll: ‘Select all’,
uncheckAll: ‘Unselect all’,
checked: ‘item selected’,
checkedPlural: ‘items selected’,
searchPlaceholder: ‘Find’,
searchEmptyResult: ‘Nothing found…’,
searchNoRenderText: ‘Type in search box to see results…’,
defaultTitle: ‘Filter cryptos’,
allSelected: ‘All selected’,
};
constructor(private appService: AppService) {
this.currencies = [‘usd’, ‘eur’]; // fiat currency options
this.selectedCurrency = ‘’; // model to store selected fiat
// array to hold names of cryptos to be used in filtering
this.cryptoCurrOptions = [];
// coinsSubject is a RxJs subject in our service that will notify us when the api has gotten data about crypto coins
this.appService.coinsSubject.subscribe({
next: (v) => this.updateCryptoOptions(v),
});
}
ngOnInit() {
}
selectCurrency(newValue) {
this.appService.loadMarketCaps(newValue);
}
filterChange(newValue) {
// BUG method should not be triggered by filter select
this.appService.updateFilter(newValue);
}
// This method creates an array of valid options for the multiselect plugin from an array of crypto coins
updateCryptoOptions(coins) {
this.cryptoCurrOptions = [];
coins.forEach((coin, index) => {
this.cryptoCurrOptions.push({
id: index,
name: coin.id.charAt(0).toUpperCase() + coin.id.slice(1)
});
});
}
}

List Component

This component manages the display of a list of cards. One for each crypto coin data returned from the api. The coins model is an array of the data to rendered by each coin. Let us update the contents of src/app/list/list.component.html

<div class=“list-cards pb-4”>
<app-list-card *ngFor=“let coin of coins” [coin]=“coin” [fiat]=“fiat”></app-list-card>
</div>
<div *ngIf=“!coins”>
{{noDataMsg || ‘Nothing to display’}}
</div>

The content of src/app/list/list.component.css is

.list-cards {
display: flex;
flex-direction: column;
align-items: center;
}

In src/app/list/list.component.ts , we subscribe to three RxJs subjects in our Service.

  • filteredCoinsSubject: Which sends updates on the filtered collection of crypto currency data. So if in the multiselect filter, only two crypto coins are selected then, the most recent value emitted by subscribing to filteredCoinsSubject will be an array of length two.
  • apiSubject : emits a string message based on api actions
  • fiatSubject : emits the value of the selected fiat currency when it is updated.
import {Component, Input, OnInit} from ‘@angular/core’;
import {AppService} from ‘…/app.service’;
import {Coin} from ‘…/coin’;
@Component({
selector: ‘app-list’,
templateUrl: ‘./list.component.html’,
styleUrls: [‘./list.component.css’]
})
export class ListComponent implements OnInit {
coins: Coin[];
noDataMsg: string;
fiat: string;
constructor(private appService: AppService) {
this.noDataMsg = ‘Select fiat currency to get started’;
this.appService.filteredCoinsSubject.subscribe({
next: (v) => this.updateCoins(v),
});
this.appService.apiSubject.subscribe({
next: (msg) => this.noDataMsg = msg,
});
this.appService.fiatSubject.subscribe({
next: (newValue) => this.fiat = newValue,
});
}
updateCoins(coins: Coin[]) {
this.coins = [];
coins.forEach((coin) => this.coins.push(coin));
}
ngOnInit() {
}
}

ListCard Component

The list-card component, is basically to display the market cap summary of a single cryptocurrency. The content of src/app/list-card/list-card.component.html is below

<div class=“card text-center mt-4”>
<div class=“card-body”>
<h2 class=“card-title”>{{ coin.id }}</h2>
<h4 class=“mb-0 pb-1”>{{fiat.toUpperCase()}} {{ coin[‘price_’+fiat] }}</h4>
</div>
<ul class=“list-group list-group-flush”>
<li class=“list-group-item”>24 hours: <span [class]="coin.percent_change_24h.charAt(0)===‘-’ ? ‘red’ : ‘green’ ">{{ coin.percent_change_24h
}}</span></li>
<li class=“list-group-item”>7 days: <span [class]="coin.percent_change_24h.charAt(0)===‘-’ ? ‘red’ : ‘green’ ">{{ coin.percent_change_7d }}</span></li>
</ul>
</div>

and src/app/list-card/list-card.component.ts

import {Component, OnInit, Input} from ‘@angular/core’;
@Component({
selector: ‘app-list-card’,
templateUrl: ‘./list-card.component.html’,
styleUrls: [‘./list-card.component.css’]
})
export class ListCardComponent {
@Input() coin;
@Input() fiat;
}

Run application

Run the application from the server tab of Angular IDE.

Conclusion

I hope you learnt a few things about Angular and Angular IDE. Thanks!


#javascript #angular.js #angular #blockchain #bitcoin #cryptocurrency

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

Riyad Amin

Riyad Amin

1571046022

Build Your Own Cryptocurrency Blockchain in Python

Cryptocurrency is a decentralized digital currency that uses encryption techniques to regulate the generation of currency units and to verify the transfer of funds. Anonymity, decentralization, and security are among its main features. Cryptocurrency is not regulated or tracked by any centralized authority, government, or bank.

Blockchain, a decentralized peer-to-peer (P2P) network, which is comprised of data blocks, is an integral part of cryptocurrency. These blocks chronologically store information about transactions and adhere to a protocol for inter-node communication and validating new blocks. The data recorded in blocks cannot be altered without the alteration of all subsequent blocks.

In this article, we are going to explain how you can create a simple blockchain using the Python programming language.

Here is the basic blueprint of the Python class we’ll use for creating the blockchain:

class Block(object):
    def __init__():
        pass
    #initial structure of the block class 
    def compute_hash():
        pass
    #producing the cryptographic hash of each block 
  class BlockChain(object):
    def __init__(self):
    #building the chain
    def build_genesis(self):
        pass
    #creating the initial block
    def build_block(self, proof_number, previous_hash):
        pass
    #builds new block and adds to the chain
   @staticmethod
    def confirm_validity(block, previous_block):
        pass
    #checks whether the blockchain is valid
    def get_data(self, sender, receiver, amount):
        pass
    # declares data of transactions
    @staticmethod
    def proof_of_work(last_proof):
        pass
    #adds to the security of the blockchain
    @property
    def latest_block(self):
        pass
    #returns the last block in the chain

Now, let’s explain how the blockchain class works.

Initial Structure of the Block Class

Here is the code for our initial block class:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()

As you can see above, the class constructor or initiation method ( init()) above takes the following parameters:

self — just like any other Python class, this parameter is used to refer to the class itself. Any variable associated with the class can be accessed using it.

index — it’s used to track the position of a block within the blockchain.

previous_hash — it used to reference the hash of the previous block within the blockchain.

data—it gives details of the transactions done, for example, the amount bought.

timestamp—it inserts a timestamp for all the transactions performed.

The second method in the class, compute_hash , is used to produce the cryptographic hash of each block based on the above values.

As you can see, we imported the SHA-256 algorithm into the cryptocurrency blockchain project to help in getting the hashes of the blocks.

Once the values have been placed inside the hashing module, the algorithm will return a 256-bit string denoting the contents of the block.

So, this is what gives the blockchain immutability. Since each block will be represented by a hash, which will be computed from the hash of the previous block, corrupting any block in the chain will make the other blocks have invalid hashes, resulting in breakage of the whole blockchain network.

Building the Chain

The whole concept of a blockchain is based on the fact that the blocks are “chained” to each other. Now, we’ll create a blockchain class that will play the critical role of managing the entire chain.

It will keep the transactions data and include other helper methods for completing various roles, such as adding new blocks.

Let’s talk about the helper methods.

Adding the Constructor Method

Here is the code:

class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()

The init() constructor method is what instantiates the blockchain.

Here are the roles of its attributes:

self.chain — this variable stores all the blocks.

self.current_data — this variable stores information about the transactions in the block.

self.build_genesis() — this method is used to create the initial block in the chain.

Building the Genesis Block

The build_genesis() method is used for creating the initial block in the chain, that is, a block without any predecessors. The genesis block is what represents the beginning of the blockchain.

To create it, we’ll call the build_block() method and give it some default values. The parameters proof_number and previous_hash are both given a value of zero, though you can give them any value you desire.

Here is the code:

def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
 def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block

Confirming Validity of the Blockchain

The confirm_validity method is critical in examining the integrity of the blockchain and making sure inconsistencies are lacking.

As explained earlier, hashes are pivotal for realizing the security of the cryptocurrency blockchain, because any slight alteration in an object will result in the creation of an entirely different hash.

Thus, the confirm_validity method utilizes a series of if statements to assess whether the hash of each block has been compromised.

Furthermore, it also compares the hash values of every two successive blocks to identify any anomalies. If the chain is working properly, it returns true; otherwise, it returns false.

Here is the code:

def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True

Declaring Data of Transactions

The get_data method is important in declaring the data of transactions on a block. This method takes three parameters (sender’s information, receiver’s information, and amount) and adds the transaction data to the self.current_data list.

Here is the code:

def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True

Effecting the Proof of Work

In blockchain technology, Proof of Work (PoW) refers to the complexity involved in mining or generating new blocks on the blockchain.

For example, the PoW can be implemented by identifying a number that solves a problem whenever a user completes some computing work. Anyone on the blockchain network should find the number complex to identify but easy to verify — this is the main concept of PoW.

This way, it discourages spamming and compromising the integrity of the network.

In this article, we’ll illustrate how to include a Proof of Work algorithm in a blockchain cryptocurrency project.

Finalizing With the Last Block

Finally, the latest_block() helper method is used for retrieving the last block on the network, which is actually the current block.

Here is the code:

def latest_block(self):
        return self.chain[-1]

Implementing Blockchain Mining

Now, this is the most exciting section!

Initially, the transactions are kept in a list of unverified transactions. Mining refers to the process of placing the unverified transactions in a block and solving the PoW problem. It can be referred to as the computing work involved in verifying the transactions.

If everything has been figured out correctly, a block is created or mined and joined together with the others in the blockchain. If users have successfully mined a block, they are often rewarded for using their computing resources to solve the PoW problem.

Here is the mining method in this simple cryptocurrency blockchain project:

def block_mining(self, details_miner):
            self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)

Summary

Here is the whole code for our crypto blockchain class in Python:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()
    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()
    def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
    def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block
    @staticmethod
    def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True
    def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True        
    @staticmethod
    def proof_of_work(last_proof):
        pass
    @property
    def latest_block(self):
        return self.chain[-1]
    def chain_validity(self):
        pass        
    def block_mining(self, details_miner):       
        self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awared with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)  
    def create_node(self, address):
        self.nodes.add(address)
        return True
    @staticmethod
    def get_block_object(block_data):        
        return Block(
            block_data['index'],
            block_data['proof_number'],
            block_data['previous_hash'],
            block_data['data'],
            timestamp=block_data['timestamp']
        )
blockchain = BlockChain()
print("GET READY MINING ABOUT TO START")
print(blockchain.chain)
last_block = blockchain.latest_block
last_proof_number = last_block.proof_number
proof_number = blockchain.proof_of_work(last_proof_number)
blockchain.get_data(
    sender="0", #this means that this node has constructed another block
    receiver="LiveEdu.tv", 
    amount=1, #building a new block (or figuring out the proof number) is awarded with 1
)
last_hash = last_block.compute_hash
block = blockchain.build_block(proof_number, last_hash)
print("WOW, MINING HAS BEEN SUCCESSFUL!")
print(blockchain.chain)

Now, let’s try to run our code to see if we can generate some digital coins…

Wow, it worked!

Conclusion

That is it!

We hope that this article has assisted you to understand the underlying technology that powers cryptocurrencies such as Bitcoin and Ethereum.

We just illustrated the basic ideas for making your feet wet in the innovative blockchain technology. The project above can still be enhanced by incorporating other features to make it more useful and robust.

Learn More

Thanks for reading !

Do you have any comments or questions? Please share them below.

#python #cryptocurrency

Ayyaz Zafar

1624138795

Angular Material Autocomplete - Multiple Use Cases covered

Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.

Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects

Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w

#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial