The Angular introduction and tutorial for beginners. Recently I was working hard to learn Angular 4 for my upcoming project needs. Technological development requires me to learn so much that I can keep up with the evolution. Lightweight, easy-to-build application system, well-organized programming structure, single page application, that’s what today’s programmers dream of.
At this time (this article was written), the Angular framework can answer all desire. Let’s look at Angular 4 tutorials for beginners along with an example project.
Table of Contents
What is an Angular Framework
Angularjs currently called Angular (ver 4) is an open-source front-end javascript framework created by Google’s Angular Team that is used to handle the large and complex web applications. Angular is a development of the older AngularJs that is more complete and powerful.
Angular is very different from AngularJs although the concept of Angular is the result of AngularJs development.
A little story, before learning about Angular (Ver 4), I first learned about AngularJs. And what I earn is a zero. I have trouble to understanding the basic concept of AngularJs because I am not a smart kid. But Angular 4 provides a different and extraordinarily structured concept so that Angular 4 is easier to learn and use. I will not go into more detail about the difference between AngularJS and Angular because it has been widely discussed on the big sites.
Angular is specifically designed to help developers build SPA (Single Page App) for complex project development. Simply put, SPA is a web application accessed through a browser but offers a more dynamic interaction that resembles desktop and mobile apps.
The biggest difference between standard and SPA websites is that SPA hardly never uses page refresh which makes the system slow. The advantage of using SPA is how to communicate with a back-end server without refreshing the page using dynamic AJAX functionality. And automatic page rendering occurs on the client side.
It looks like my intro is too long, okay we just start Angular 4 tutorial create a simple app to display the list of items using PHP REST API and Angular
Initial preparation:
1. install node.js and NPM
To install node.js, I have discussed in the previous article. You can read it through the following article
- Tutorial Create CRUD With Node.Js, Express, MySQL, And AdminLTE For Beginner
- https://nodejs.org/en/download/package-manager
Why does Angular 2 need Node.js and NPM?
Node.js and NPM are not required to run Angular applications. However, this is required as a development environment before we can do anything. Some reasons why need it:
TypeScript: Angular uses typescript which is then compiled into the .js extension. Typescript is a superset of JavaScript, and it’s compiled to JavaScript anyway.
Web Server: Node.js is used as a web server before it is compiled as a production file.
Reference : https://stackoverflow.com/questions/37267510/why-do-we-have-install-node-js-for-Angular-2-0
2. Install Angular cli
Angular cli is the command-line interface for Angular. The Angular CLI requires all of the configuration and setup.
1 | npm install -g @Angular/cli |
Reference : https://github.com/Angular/Angular-cli#installation
3. Install Visual Code Editor
The visual code editor is an IDE created by Microsoft. Using this IDE is an appropriate step where typescript is an open source project supported by Microsoft. So using IDE and Project in one package is a smart step. Please download the Visual Code Editor at https://code.visualstudio.com/
4. Mysql Database and Data Preparation
As a material of this example project, we use MySQL as a data container. For the initial preparation, we will use a database that I often use in previous articles, namely “pos” database. Please visit Tutorial Build Point Of Sale With PHP, PDO, MySQL And Jquery Part 1 for database preparation.
1 2 3 | insert into 'm_item' ('id_item', 'item_name', 'note', 'stock', 'price', 'unit') values('PB0001','Razor Blade','best razor blade in the world','8.00','12000','PCS'); insert into 'm_item' ('id_item', 'item_name', 'note', 'stock', 'price', 'unit') values('PB0002','Muscle Face','for build body','10.00','50000','PCS'); insert into 'm_item' ('id_item', 'item_name', 'note', 'stock', 'price', 'unit') values('PB0007','GALAXY NOTE 1','test 1 2 3 4 5 6','5.00','5000','PCS'); |
5. Make a Simple REST API
I use PHP as the backend server of this Angular tutorial to create a simple REST API. I am not discussing further the creation of this REST API because I have discussed in previous articles in Rest API And HTTP Methods (GET, POST, PUT, DELETE) Using Slim Framework And PHP. But you can download REST API Project as a supporting file of this tutorial here.
If the five steps above have been completed, the next step we create the main application.
Create a simple application to display product list using Angular 4, Rest API PHP and MySQL
# Create an Angular project
Create new project with Angular cli with following code in the terminal or command prompt
1 | ng new learnangular4 |
After create new project, please go to on the learnangular4 folder
# Create an interface
What is an interface? Please read here about the interface description. In essence, an interface is a class that can be used as a variable type.
Copy the following code to create an interface on the terminal or command prompt
1 | Ng generate interface interfaces/items |
And then copy the following script in the items.ts
1 2 | export interface Item { } |
# Create a service
In Angular, a service is a function, or object, that is available for, and limited to, your Angular application.
We will create services that are used to communicate with REST API Server that we have prepared before.
Copy the following code to create the service in the terminal or command prompt
1 | Ng generate service service/servicedata |
Then copy the following code in data.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import { Injectable } from '@angular/core'; import {Http, Response, RequestOptions, Headers } from '@angular/http'; import {Observable} from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class DataService { constructor(private http:Http) { } getItem():Observable<any>{ const url = 'http://localhost/restapiserver/api/get/item/list'; return this.http .get(url, {}) .map( res => { const data = res.json(); return data; }, err => { return err; } ) } } |
A brief description:
To communicate with REST API Server, Angular requires functions that can be used to communicate with the backend server. The function called httpclient .
In essence, using the RxJs Observable library makes it easy for Angular to process data from HTTP requests. I am not clever to explain in detail, you can learn about the full observable on the site https://scotch.io/tutorials/Angular-2-http-requests-with-observables. I also learned from there.
# Make 2 pieces of component
The Component brief description.
Angular Component is a special command type that uses a simple configuration suitable for the structure of component-based applications.
This makes it easier to write applications in a similar way to using Web Components or using the new Angular application architecture.
Advantages of Components:
- Configuration is simpler than regular commands.
- Promote smart defaults and best practices.
- Optimized for component-based architecture.
- Writing component directives makes it easy to upgrade to Angular
Reference: https://Angular.io/api/core/Component
Create the first component of the listitem, use the following commands to create the component in the terminal or command prompt
1 | ng generate component item/listitem |
From the above command will create 4 pieces of new files like the following picture
Open the listitem.component.ts file and add the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import { Component, OnInit } from '@angular/core'; import { DataService } from '../../service/data.service'; import { Item } from '../../interfaces/item'; @Component({ selector: 'app-listitem', templateUrl: './listitem.component.html', styleUrls: ['./listitem.component.css'], providers: [DataService] }) export class ListitemComponent implements OnInit { public listitem; public containeritem:Item; constructor(private dataservice:DataService) { } ngOnInit() { this.dataservice.getItem().subscribe( res =>{ this.listitem = res.data[1]; }, err =>{ console.log("There is an error : "+err); } ) } onSelect(item:Item){ this.containeritem = item; } } |
Open the file listitem.component.html and add the following HTML code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <div class="row"> <div class="small-3 columns"> <p> List Item : </p> <ol *ngIf="listitem"> <li *ngFor="let item of listitem" (click)="onSelect(item)" >{{item.item_name}}</li> </ol> </div> <div class="small-9 columns"> <app-detailitem [Inputitem]="containeritem"></app-detailitem> </div> </div> |
A brief description:
Listitem.component.ts is the main component used to display list items.
Listitem.component.ts will call servicedata service that has been created to communicate with the server backend.
The product data will be accommodated into the listitem variable then displayed in the HTML template.
Listitem.component.html is an HTML template that will displayed on the browser screen
The second component is detailitem, use the following code to create the component
1 | Ng generate component item/detailitem |
From the above command will create 4 pieces of new files like the following picture
Open the file detailitem.component.ts and add the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import { Component, OnInit,Input } from '@angular/core'; import {Item} from '../../interfaces/item'; @Component({ selector: 'app-detailitem', templateUrl: './detailitem.component.html', styleUrls: ['./detailitem.component.css'] }) export class DetailitemComponent implements OnInit { @Input() Inputitem:Item; constructor() { } ngOnInit() { } } |
Open the file detailitem.component.html and insert the following HTML code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <p> Detail Item : </p> <div *ngIf="Inputitem"> <dl> <dt>ID Item</dt> <dd>{{Inputitem.id_item}}</dd> <dt>Name</dt> <dd>{{Inputitem.item_name}}</dd> <dt>Price</dt> <dd>{{Inputitem.price}}</dd> <dt>Stock</dt> <dd>{{Inputitem.stock}}</dd> <dt>Unit</dt> <dd>{{Inputitem.unit}}</dd> <dt>Note</dt> <dd>{{Inputitem.note}}</dd> </dl> </div> |
A brief description:
This component is used to display item details.
In this component, we learn to use @input() decoration. @Input() decoration performs bindings to component members within template expressions and statements that appear on the right side of the binding declaration
# Styling you app
The final step of this tutorial, we will set the application to appear neat and good.
To facilitate my styling using the Foundation CSS Framework. Add the following CDN to the index.html file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Learnangular4</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.2/css/foundation-float.css"> </head> <body> <div class="row"> <app-root></app-root> </div> </body> </html> |
Edit styles.css and insert the following CSS script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /* You can add global styles to this file, and also import other style files */ @import url('https://fonts.googleapis.com/css?family=Muli:400,700'); body { background:#e8e8e8; font-family: 'Muli'; padding: 10px; } li{ padding:5px; cursor: pointer; } li:hover{ background-color: #F6FFDE; } |
Done! Please test your app with script below
1 | ng serve |
Or if you want to run from the other pc please use the following script
1 | ng serve --host 192.168.1.20 |
192.168.1.20 is my current ethernet IP Address, change with yours
If successfully, open your browser and run http://localhost:4200 in the url address
Conclusion
Understanding angular 4 is not as difficult as we imagine. Many guides or tutorials have been shared through youtube or google search engine. Also, Angular 4 has implemented the MVC concept even though its use is slightly different from the existing MVC concept. This causes the structure of the program we create to be more neat and structured.
You can download example project using the download link below. Please help me to share this article with those who need it by sharing the article through share button below.
[sociallocker id=58]
Example project tutorial angular 4 for beginner
[/sociallocker]
Leave a Reply