24 April 2020

Angular 2 Intro

Features of Angular 2
Components: focus is shifted from controllers in earlier version to components. components help to build applications into many modules and make application easy to maintain.
TypeScript: newer version of angular is based on typescript it is superset of javascript and is maintained by Microsoft.
Services: it is piece of code that can be shared by different components of an application. for example if there is data component that picked up data from DB, then it can be set as shared service to use it across application.
Angular 2 Directives:
directive is custom HTML element that is used to extend power of HTML. Angular 2 has below directives as part of BrowserModule module
ngIf
syntax: *ngIf = 'expression'
ngFor
syntax: *ngFor = 'let variable of variableList'
These are used as part of html elements to display based on condition specified in for loop or if condition.
routing in angular
based on option user choose on main page the corresponding component gets rendered.
what is CLI
Command line interface used to create angular application using commands. it also helps to create unit tests or end to end tests.
Dependency Injection
Ability to add functionality of component at runtime.
example:
create a class with  injectable decorator  and in any module where you want to use the service, you need to define as provider in the component decorator.
Example:

@Injectable()
export class classX {
}
 
@Component ({
    providers : [classX]
})

package.json file contain information about Angular 2 project.
systemjs.config.json file loads all necessary infomation without need to add script tag to html pages.
app.module.ts
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
 
@NgModule({
    imports : [BrowserModule],
    declarations : [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module.
The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options.
The BrowserModule is required by default for any web based angular application.
The bootstrap option tells Angular which Component to bootstrap in the application.
Convert String to lowercase/uppercase/Date/currency/percentage
The name of this tutorial is {{tutorialname}} The first topic is {{tutorialname | lowercase}} converting to uppercase {{tutorialname | uppercase}} date value is {{newdate | date:"MM/dd/yy"}} amount {{amount | percent}} final amount {{amount | currency}}
ngOnChanges event gets called when a data bound property changes its value.
ngOnInit event : during initialization of component.
ngDoCheck event
ngAfterContentInit event gets called when external content gets loaded to a component view.
npm = node package manager is used to download packages/dependencies on other components useful to run angular project.
How to setup Angular 2 Environment:
Go to below website, download and install node.js
run below command from command prompt to check version of node
$node version
download Visual Studio Code tool / editor from below link
Sample Application Run:
create a directory with name Project_practice directory and Demo folder inside it.
now go to command prompt and traverse to Project_practice directory and run below command to clone the git project
$git clone https://github.com/angular/quickstart Demo
Now go to Demo directory and run npm install to install necessary packages to run AngularJS application.

Now run below command to start the web application
npm start
app.module.ts file in src/app directory is root module class. it contains NgModule decorator to set imports declarations, bootstrap.
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'
import { AppComponent }  from './app.component'
 
@NgModule ({
   imports:      [ BrowserModule ],
   declarations: [ AppComponent ],
   bootstrap:    [ AppComponent ]
})
export class AppModule { }
Each Angular 2 application made of modules and the root module is made of components. each component specific to each task.
Components are a logical piece of code for Angular JS application. A Component consists of the following:
Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application.
Class − This is like a class defined in any language such as C++/Java in typescript. This contains properties and methods. This has the code which is used to support the view.
Metadata − This has the extra data defined for the Angular class. It is defined with a decorator.
import { Component } from '@angular/core';
 
@Component ({
   selector: 'my-app',
   template: ` <div>
      <h1>{{appTitle}}</h1>
      <div>To Tutorials Point</div>
   </div> `,
})
 
export class AppComponent {
   appTitle: string = 'Welcome';
}
In the component we can even use templateUrl instead of template by passing html page url as below:
templateUrl: 'app/app.component.html' 
here selector is the custom html tag to be used in index.html as below. template is the  view. class got exported so that we can use it in other components.
<body>
   <my-app></my-app>
</body>
Data Binding
example to display images and binding them
app.component.ts
import { Component } from '@angular/core';
 
@Component ({
   selector: 'my-app',
   templateUrl: 'app/app.component.html',
   styleUrls : ['app/app.component.css']
 })
 
export class AppComponent {
   appTitle: string = 'Welcome';
   appList: any[] = [ {
      "ID""1",
      "url"'app/Images/One.jpg'
   },
 
   {
      "ID""2",
      "url"'app/Images/Two.jpg'
   } ];
}
app.component.html
<div *ngFor = 'let lst of appList'><ul><li>{{lst.ID}}</li>
<img [src] = 'lst.url'></ul></div>
Forms:
Angular CLI (https://cli.angular.io/): The Angular CLI makes it easy to create an application that already works, right out of the box. It already follows our best practices! install python and run below command from terminal to install angular cli npm install -g @angular/cli this make creating project easy: ng new Demo3 //It will automatically create the files and start downloading the necessary npm packages. Demo3 is project name here. ng serve // this will run the project
to generate dist
ng build   // to generate dist directory asset.config  file
node server.js  //  to read server.js and run output in 8080 port
Dependency Injection:
Data Binding on html tag example:
which is binding on the fly is the use of the input html tag. It just displays the data as the data is being typed in the html tag. Make the following changes to the app/app.component.html file which is your template file.
<div>
   <input [value] = "name" (input) = "name = $event.target.value">
   {{name}}
</div>
 
 
<div>
   {{Status}}
   <button (click) = "clicked()">Click</button>
</div>
more details of above code:
[value] = ”username” − This is used to bind the expression username to the input element’s value property.
(input) = ”expression” − This a declarative way of binding an expression to the input element’s input event.
username = $event.target.value − The expression that gets executed when the input event is fired.
(click) = "method call" this will call the method defined in corresponding component class for which this template belongs to.
Data Transformations that can be used in displaying values in template/html:
Propertyvalue | lowercase
Propertyvalue | uppercase
propertyvalue | date:"dateformat" where date format is like "dd/mm/yy"
propertyvalue | slice:start:end  where start is start position and end is end position
propertyvalue | currency
propertyvalue | percent
 
Example:
<div>
value of x is {{propertyvalue | uppercase}}
</div>
Custom Pipes in Angular:
Angular 2 also has the facility to create custom pipes. The general way to define a custom pipe is as follows.
import { Pipe, PipeTransform } from '@angular/core'
@Pipe({name: 'Pipename'})
 
export class Pipeclass implements PipeTransform {
   transform(parameters): returntype { }
}
Where,
'Pipename' − This is the name of the pipe.
Pipeclass − This is name of the class assigned to the custom pipe.
Transform − This is the function to work with the pipe.
Parameters − This are the parameters which are passed to the pipe.
Returntype − This is the return type of the pipe.
Ensure the custom pipe is added to declarations of app.module.ts, so that we can use it in any of the component template html file.
import {   NgModule } from '@angular/core';
import {    BrowserModule } from '@angular/platform-browser';
import {    AppComponent } from './app.component';
import {    MultiplierPipe } from './multiplier.pipe'
 
@NgModule ({
   imports: [BrowserModule],
   declarations: [AppComponent, MultiplierPipe],
   bootstrap: [AppComponent]
})
 
export class AppModule {}
The Root Module (app.module.ts)
@NgModule({
    imports : [
            BrowserModule       //need for any web application
],
declarations : [
            AppComponent     // Any directive / pipe / component used by view/html file need to be declared here.
    ],
bootstrap : [AppComponent]   //initiated from other file called main.ts
})
export class AppModule {}
How Angular2 flow works
(first it executes main.ts which invokes app.module which loads component specified in bootstrap then loads the component code)
main.ts --→  app.module.ts --→ app.component.ts
command to run the application:
ng serve
command to run karma test cases:
ng test
Some commands in angular:
how to check the version of Angular CLI
Ex: ng --version
To remove angular/cli
Ex: npm remove @angular/cli
To install angular/cli:
npm install --save-dev@angular/cli@latest
To check version of webpack:
npm list webpack
to remove webpack:
Ex: npm remove webpack
To install webpack of specific version only:
npm install webpack@3.11.0
install with --save-dev
npm install --save-dev @angular/cli@v6.0.0-rc.4
References:

No comments:

Post a Comment