Angular 2.0 With completed Hands-on
Introduction to Angular 2
In this course, you will explore Angular 2, which is a sequel to Angular 1.x with numerous enhancements. You will briefly go through the following concepts.-
Introduction to Angular 2 -Architecture
- Environment Setup
- Module
- Component
- Template
- Metadata
- Data Binding
- Service
- Directives
- Dependency Injection
What is Angular 2?
- It is a JavaScript framework for creating web and mobile applications.
- It supports TypeScript, a super script of Javascript that helps in safe coding.
- It has several enhancements on top of Angular 1.x, which makes it simple to use and get the desired output. But knowledge in Angular 1.x is not necessary to learn Angular 2, since the whole framework is re-written.
Why Angular 2?
- Easy: Unlike previous versions, Angular 2 focuses only on building JavaScript classes; hence it is easier to learn.
- Freedom: It provides more choices of languages for consumption i.e. ES5, ES6, Typescript, and Dart. TypeScript is recommended here.
- Flexible: It is a Cross-platform framework.
- Faster: Because of server side rendering.
- Simpler: Component based approach with no controllers and $scope.
- Performance: Uses Hierarchical Dependency Injection system, which is a performance booster.
Angular 2 Environment Setup
- To setup an Angular 2 environment, node.js is mandatory. Once node.js and npm are available, you can run the following to complete the setup in cmd.
- Install Angular CLI(command line interface) Command: npm i -g @angular/cli (-g installs angular globally for all users)
- Install TypeScript Command: npm install -g typescript
What is Module?
- A Module is a way of organizing related Components, Services, Directives, and Pipes with a specific functionality.
- It is a block of code meant to do certain tasks.
- There can be several Modules within an app, but it should consist of at least one root module. Root Module, by convention, must be named: AppModule.
- It can be exported and imported in other modules.
@NgModule is used to declare a Class as Module.
Module as library - Angular Module can act as a library of modules. @angular/core is a most common library being used in building angular application. It has most of the modules that are required for your app.
Module - Example
This is a sample code for module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
// AppModule Class is now defined as Module : @NgModule
Trick to identify Root Module is that it imports "BrowserModule". Other modules of that same application imports "CommonModule".
imports:[...] - define array of modules required to build application here.
declarations:[...] - define components, directives and pipes for this module here.
bootstrap:[...] - define root component of this module here.
What is Component?
- A component is the basic block of angular 2 app.
- It handles the view part of the app and has the core logic of the page.
- It can render the view by itself based on the dependency Injection.
- There can be only one component per DOM element (i.e. only one selector element).
- Element's behavior can be manipulated by the properties associated with corresponding component.
- It can be identified using the decorator @Component.
- Components can be created, updated or destroyed based on the user actions on the page.
Components - Example
This example will render Hello, World! in the browser. Angular will search for <my-app> element in HTML file and replace it with the template content.
File: app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<p>Hello, World!</p>',
})
export class AppComponent{}
File: index.html
............
<body>
<my-app> Loading... </my-app>
</body>
............
What is Template?
Template is a simple HTML code that creates view for a component, which you can dynamically manipulate.
There are two ways to define templates:
- template
- templateUrl
How to use Template?
When template is used, it defines code in the same file
import {Component} from 'angular2/core';
@Component({
selector: 'greet',
template: `
//this defines template for 'greet' component
<h1>Hello There!!!</h1>
<h2>Have a nice day.</h2>
` // back tick symbol (~ key on your keyboard)
//back tick is explained in detail in TypeScript
})
export class GreetApp {}
When templateUrl is used, the code is defined in different files and URL of the corresponding files are referred.
import {Component} from 'angular2/core';
@Component({
selector: 'greet',
templateUrl: 'app.component.html'
//this defines "URL to the external file"
that defines template for 'greet' component
})
export class GreetApp {}
Hands-on 1 : Create an Angular application
file : app.component.ts
import { Component } from '@angular/core';
@Component({
// Add your code here for both selector and template
selector:'app-root',
template:'<h1>My first angular app</h1>'
})
export class AppComponent {}
What is Metadata?
In Angular 2, Metadata is vital in getting the code processed and shown on the screen. Metadata means data of data, which gives more info about data.
ex: var age : number = 20;
// 20 is data
// "number" is metadata, as it tells information of "data", its type, its size etc.
Metadata - Example
- Let us consider a simple example code as shown below. Suppose you want to have a component, Angular will consider it as a simple "class" until you explicitly use "Decorator" and attach metadata to TypeScript.
- Here, @Component is used to define a class as component.
- Likewise, @pipe is used to tell Angular to define a class as pipe.
import {Component} from 'angular2/core';
@Component({ //METADATA
selector: 'greet',
template: `
<h1>Hello There!!!</h1>
<h2>Have a nice day.</h2> `
})
export class GreetApp {}
Simply put, everything in Angular 2 is a simple class, until you declare metadata (@Component or @Pipe or @Decorator or @Injectable) to it.
What is Data Binding?
It is the process of automatic synchronization of view and business logic. It helps in connecting the Template (view - what user sees) with Component (back end data/source).
There are four ways you can bind a data to the DOM depending on the direction the data flows.
- Data flows into the view by Interpolation and Property Binding.
- Data flows outside the view into the class by Event Binding.
- Data flows both ways by Two-Way Data Binding.
- Data Flow (Out of the viwe)
String interpolation :
{{title}} (always resolves to a string)
Property Binding :
<input [required]='expression'>
Even Binding :
<button(click)='expression/function'>
Component class can handle the event
Two way data binding :
<input[(ngModel)]="model/object>
Update the model/object in the component class
In turn updatesany reference to the model/object in the view template
{{model}}
Interpolation
- Interpolation acts as local variable, which allows us to bind data from "Component Class" onto your "Template".
- It is defined using {{ }} double curly braces.
- If we consider an example, 20 + 20 results in {{20 + 20}}, the actual mathematical calculation is done and output is displayed as 20 + 20 results in 40.
- It can also access values from component class. Ex - {{myName}}
- It can further assign attributes to the tags. Ex - <img src = {{myImageURL}}>
Hands-on 2 : Interpolation in Angular
File : app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<h1>{{message}}</h1>'
})
export class AppComponent {
message = 'hey there';
}
Property Binding vs Interpolation
Both are same, as they make the data flow from "Component" to "Template". The only difference is the way they are defined or used.
Interpolation Demo
import { component } from `@angular2/core`;
@Component ({
selector: 'myApp',
template: `
<h1> {{title}} </h1> //Interpolation Binding `
})
export class AppComponent {
title: "Hello Fresco !"
}
Property Binding Demo
import { component } from `@angular2/core`;
@Component ({
selector: 'myApp',
template: ` <h1 [innerHtml] = "title"> </h1> //Property Binding `
})
export class AppComponent {
title: "Hello Fresco !"
}
Hands-on3 : Property Binding in Angular
File : app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html' // refer app.component.html for adding message value using property binding
})
export class AppComponent {
message="hey there";
//Define your message with hey there
}
File app.component.html
<span [innerHtml]="message"></span>
Event Binding
- User interaction on view generates "Events" that make data flow from "Template" to "Component". It is defined using () parantheses. The following video will explain Event Binding in detail.
- Bind events to HTML element
- Binding to native events (such as a click events)
<button(click)="function"> - Bind to custom events we make
<app-home (update)="function"></app-home>
Hands-on 4 : Event Binding in Angular
File : app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html' //// refer app.component.html for property binding
})
export class AppComponent {
name ="John Doe";
//Define your name and show variables here
//Define your welcomeMe(username) method here
welcomeMe(username : string){
this.name = username
}
}
File : app.component.html
Enter Your Name:
<input #userName type="text" value='John Doe'>
<button #btn (click)=welcomeMe(userName.value)> Welcome Me </button>
<br>
<h2> Message from Event Binding</h2>
<h3 id="output">
<!--add your welcome message with name like `Welcome <name>`-->
Welcome {{name}}
</h3>
Two-Way Data Binding
- Property Binding and Event Binding are One Way Data Binding. In other words, data will flow either from Component to View or the other way, but not both.
- Two-way data binding is a combination of both Property Binding and Event Binding allowing us to update data in both directions. It is defined using [( )] popularly known as banana brackets.
Hands-on 5 : Two-way Data Binding in Angular
File : app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
//Define your name object with first and last properties
name = {
first : "John",
last : "Smith"
}
}
File : app.component.html
Enter Your Name:
<input id="firstName" type="text" [(ngModel)]="name.first">
<input id="lastName" type="text" [(ngModel)]="name.last">
<br>
<h2>Message from Two way Binding</h2>
<h3 id="output">
<!--add welcome message here with first and last values of name-->
<h3>Welcome {{name.first}} {{name.last}}</h3>
</h3>
What are Directives?
Directive is a class with @Directive decorator. They make DOM elements dynamic, by changing their behavior.
Directive is of three types:
- Structural,
- Attribute and
- Component.
Structural Directive
- They manipulate the DOM elements. i.e. Delete or update the elements. This changes the structure of webpage.
- Some of the built-in structural directives, Angular 2 offers are NgIf, NgFor and NgSwitch.
Example: <div *ngIf="employee">{{employee.name}}</div>
Attribute Directive
- These directives add styling by manipulating the Attributes of DOM element. They do not change the structure of webpage.
- NgStyle and NgClass are some of the built-in attribute directives, Angular 2 provides.
Example :
File : app.component.html
or
File: app.component.ts
When use hidden or *ngif ?
Hands-on 6 : Directives in Angular :
File : app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
public show : boolean;
public message:string;
public selectedDay : number;
public selectedValue : string;
days = [{today:"Monday", msg:"Marvelous Mondays!"},
{today:"Tuesday",msg:"Thrilling Tuesday!"},
{today:"Wednesday",msg:"Wonderful Wednesday!"},
{today:"Thursday",msg:"Trendy Thursdays!"},
{today:"Friday",msg:"Fantastic Friday!"},
{today:"Saturday",msg:"Super Saturday"},
{today:"Sunday",msg:"Sunny Sunday"}];
//Define your constructor here with selectedDay as 0
constructor(){
this.selectedDay = 0;
}
}
What is Service?
Services are functions that are designed to complete a specific task. If you want to bring external data from server into your app or perform some repetitive task, then services come handy.
How to use Services?
- Create a file <serviceName>.services.ts.
- Import injectable from @angular/core.
- Create a class with the required function and use the decorator @injectable() to specify that it is a service.
- Then import the service in root component, which is discussed in Dependency Injection.
Example: This simple service will perform add operation whenever it is used.
import {Injectable} from 'angular2/core';
@Injectable()
export class MyService {
addFunction(a,b){ return a+b; }
}
Hands-on 7 : My Activity Tracker in angular:
File : app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
//Define your variables done,todos,newToDo,newToDoObj,error
todos :any;
done : boolean;
newToDo : string;
newToDoObj : any;
error : boolean;
TODOS : any[]
//Define your constructor here with todos as [] ,newToDo as '' and error as false
constructor(){
this.todos = [];
this.newToDo = '';
this.error = false;
}
//Define your addMore function here
addMore(newToDo){
if(this.newToDo != ''){
this.newToDoObj = {
newTodo : this.newToDo,
done : false
}
this.todos.push(this.newToDoObj);
this.newToDo = '';
}else{
this.error = true;
}
}
//Define your clearAll function here
clearAll(){
this.todos.length = 0;
}
}
Pipe :
Angular provides built-in pipes for typical data transformations,
including transformations for internationalization (i18n), which use
locale information to format data.
The following are commonly used built-in pipes for data formatting:
DatePipe
: Formats a date value according to locale rules.UpperCasePipe
: Transforms text to all upper case.LowerCasePipe
: Transforms text to all lower case.CurrencyPipe
: Transforms a number to a currency string, formatted according to locale rules.DecimalPipe
: Transforms a number into a string with a decimal point, formatted according to locale rules.PercentPipe
: Transforms a number to a percentage string, formatted according to locale rules.
pipe Example : Courses.component.ts
File - Favorite.component.ts
How to create Manually TitleCase Pipe ?
File : titlecase.component.html
Component API:
File : course.component.html
<favorite [isFavoraite]="post.isFavorite"></favoraite>
Error :
../course/course.component.html:1:9 - error NG8002: Can't bind to 'isFavorite'
since it isn't a known property of 'course'.
File : course.component.ts
import { Component, OnInit } from '@angular/core';
Difference between Reactive Form and Template Driven Form?
[formGroup]="loginForm" (ngSubmit)="loginUser()">
--------------------------------------------------------------------------------------------------------------------------
WOW
ReplyDelete