Archive
Angular 5.0 New things
Angular team has released Angular 5.0 on 1st Nov 2017.
They focused on most new features and bug fixes. This release continues our focus on making Angular smaller, faster, and easier to use.
Following things are New:
Angular CLI 1.5 and Angular 5.0.0
Now we are in CLI 1.5, if you install CLI 5.0, automatically you will get the angular 5.0 versions default in your package.json file in angular app.
Typescript updated to 2.4
Dynamic import expressions are a new feature and part of ECMAScript that allows users to asynchronously request a module at any arbitrary point in your program.
RXJS was updated to 5.5 version:
This recent release of RxJS fully empowers developers to avoid the side effects of the
previous import mechanism with a new way of using RxJS called “lettable operators”.
These new operators eliminate the side effects and the code splitting .
Tree shaking problems that existed with the previous ‘patch’ method of importing operators.
instead of :
import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/filter'; names = allUserData .map(user => user.name) .filter(name => name);
user below like this:
import { Observable } from 'rxjs/Observable'; import { map, filter } from 'rxjs/operators'; names = allUserData.pipe( map(user => user.name), filter(name => name), );
Buid optimizes.,Bundle size reduced, Speed the app
Ahead -of -time compiler
Converts your angular code before browser downloads and run it
Aot: faster rendering . few async reauests, smaller download
watch mode files ngc –watch. This command will watch your file what are the file executing
Easier to build progressvie web apps
The build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decreases the size of your JavaScript bundles, and increases the boot speed of your application for your users.
Their goal is to make this angular default option for most developers
->service workers
->small, easier and more powerfull
->Http client module feature added. from
import { HttpClientModule } from '@angular/common/http';
removed map(res=> res.jon()) calls which no longer needed with http client module.
depreacted http in 5.0 version, for now you can use http in 5.0 but its depreacted. In future they may removed from angular 5.0
Angular Form validation
They added some new feature on forms.
angular 4 form validates the form when we entered the characters.
but in angular 5 they inclueded validation on blur and submit
validation and value updates on `blur` or on `submit`, instead of on every input event
Template Driven Forms
Before
<input name="firstName" ngModel>
After
<input name="firstName" ngModel [ngModelOptions]={updateOn: 'blur'}>
OR
Validations will be done on submit.
Or you can add for each individual with ngModel options
<input name ="firstName" ngModel[ngModelOptions]={updateOn: 'blur'}>
Or simply you can use the reactive forms
Reactive Forms
Before
new FormGroup(value); new FormControl(value, [], [myValidator])
After
new FormGroup(value, {updateOn: 'blur'})); new FormControl(value, {updateOn: 'blur', asyncValidators: [myValidator]})
Changes with pipes
DepreactedI 18 Npipes module
old pipes will depreacted but you can use now. In future they may removed from angular 5.0
Increase standardization across browsers
Internationalized Number, Date & Currency
Router Life cycle Events:
New lifecycle events to the router, allowing developers to track the cycle of the router from the start
of running guards through to completion of activation. These events could be used for things such as showing a spinner on a specific router outlet when a child is updating or to measure performance of guards and/or resolvers. Allow develpers to track the routing cycle used to do things like show spinners, measures performance of guards
GuardsCheckStart, ChildActivationStart, ActivationStart, GuardsCheckEnd, ResolveStart, Resolve End,
ActivatonEnd, ChildActivationEnd
An example of using these events to start/stop a spinner might look like this:
class MyComponent { constructor(public router: Router, spinner: Spinner) { router.events.subscribe(e => { if (e instanceof ChildActivationStart) { spinner.start(e.route); } else if (e instanceof ChildActivationEnd) { spinner.end(e.route); } }); } }
Angular Universal State Transfer API and DOM Support
Easily share application state between the server side and client side versions of your application.
And helping developers to perform server side rendering (SSR) of Angular applications.
By rendering your Angular applications on the server and then bootstrapping on top of the generated HTML, you can add support for scrapers and crawlers that don’t
Support JavaScript, and you can increase the perceived performance of your application.
In 5.0.0, the team has added ServerTransferStateModule and the corresponding BrowserTransferStateModule. This module allows you to generate information as part of your rendering with platform-server, and then transfer it to the client side so that this information does not need to be regenerated
This means when you fetch the data over http, by transfer data from there server, this means developers no need to make 2nd HTTP request
It supported more DOM manipulations out of the box within server side contexts, improving our support for 3rd party JS and Component libraries that aren’t server-side aware
Improvements on compiler:
They improved compiler to supports incremental compilation. Its provide faster rebuilds,
It builds with AOT, and added new feature to Decorators. And made it possible to smaller bundles
By remove the whitespaces.
Typescript Transforms
Typescript transform, making incremental rebuilds dramatically faster
You can take advantage of this by running ng serve with the AOT flag turned on.
You can take advantage of this by running ng serve with the AOT flag turned on.
ng serve –aot
This will become the default in a future release of the CLI
On this transforms, we don’t need a genDir anymore, and outDir has been changed: we are now always emitting generated files for packages in node_modules.
Preserve Whitespace
Tabs, newlines, and spaces in your templates are recreated and included in the build by the compiler.
You can now choose whether or not to preserve whitespace coming from your components and your application.
1) You can specify this as part of each component’s decorator, where it currently defaults to true.
@Component({ templateUrl: 'about.component.html', preserveWhitespaces: false } export class AboutComponent {}
2) specify in tsconfig.json file also: by default its true.
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "es2015",
"types": []
},
"angularCompilerOptions": {
"preserveWhitespaces": false
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
Decorator Support :
Expression lowering in decorators for lambdas and the value of useValue, useFactory and data in object literals. This allows you to use values that can only be calculated at runtime in decorators for expressions that are lowered.
You can now use a lambda instead of a named function, meaning you can execute code without affecting your d.ts or your public API.
Component({ provider: [{provide: SOME_TOKEN, useFactory: () => null}] }) export class MyClass {}
-> lower expressions as part of useValue.
Component({ provider: [{provide: SOME_TOKEN, useValue: SomeEnum.OK}] }) export class MyClass {}
Replace the ReflectiveInjector with StaticInjector
In order to remove even more polyfills, we’ve replaced the ReflectiveInjector with the StaticInjector.
This injector no longer requires the Reflect polyfill, reducing application size for most developers.
Before
ReflectiveInjector.resolveAndCreate(providers);
After
Injector.create(providers);
Please refer angular blog for more info:
https://blog.angular.io/version-5-0-0-of-angular-now-available-37e414935ced
update to angular 5.0 from this below site
If you want to update your angular app to 5.0, just go to below website and give your current version in the fields.
Angular 4: Service example
Welcome to Angular 4 services
Angular services are for building out code that can be shared across multiple components. And these are singletons. services restrict the instantiation of a class to one object. It means the methods and properties can be shared throughout your application from a single shared instance.
These services are best way to store the session data and perfect place to call the web services. And the data is shared to the components with the injecting service. Without hitting the web services we can use the session data in the application. But If you refresh the browser the session service data will be empty. So remember that condition.
In this tutorial, we provide a basic angular 4 service example using the Angular CLI.
We’ll be using the Angular CLI to create our app. Create a new Angular project by running:
ng new AngularServiceEx
This will create the new project named as AngularServiceEx project.
And navigate to root application by cd AngularServiceEx. And run the below command
npm install
This command will download all your dependencies from your package.json file.
And run the below command to create the service in the project.
ng g service reference
It will create the reference.service in the ’app’ folder automatically. We don’t need to do anything. It will create the two files in our Angular app
- a reference.service.tsfile under the src/app directory
- a reference.service.spec.tsfile under the src/app directory
We will write the service code in the service.ts file. And service.spec.ts file will used for unit testing.
The ng g service command won’t automatically configure your root module app.module.ts to provide the service.
Services must import the Injectable from the angular/core package, like below. see the angular. io website for more info on services.
import { Injectable } from ‘@angular/core’;
And services uses the injectable decorator. @Injectable() . The @Injectable decorator simply provides dependency injection for the service.
Don’t forget to add the decorator in the service.ts file. If we don’t add it will not work.
Service must have the export keyword. Everything like class or component should use ‘export’ keyword. Then only it is possible to use the class or component or anything in the project. And service name should end with .service. For ex: reference.service.ts file. If we have lengthy name we need add the ‘–‘ in the service name. That is for code readability.
Example: save-user-info.service.ts
Service structure:
import { Injectable } from '@angular/core'; @Injectable() export class ReferenceService { constructor() { console.log(“welcome! Reference Service”); } }}
To include the service in your app, you must import it and include it as a provider in app.module.ts or we can add the service in providers of component meta data also. But it will be available in the particular component only. But it’s better to use the service in the providers of app.module.ts. Service will create the instance every time, whenever you come to the component. By registering the service as a provider, you make it available everywhere in the application.
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { ReferenceService } from './reference.service' @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [ReferenceService], bootstrap: [AppComponent] }) export class AppModule { }
Accessing the Service from a component:
app.component.ts
Services must be imported by the component. We will import our reference service in open the auto-generated app.component.ts and replace it with the following:
import { Component } from '@angular/core'; import { ReferenceService } from './reference.service' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(public reference: ReferenceService){ } }
Service with HTTP methods :
We will have to interact with Database to get the data and post the data. For that we will write the web service api in the Angular services. We will have to call the HTTP POST or HTTP GET methods with REST API in the service to store that data in the DATABASE or retrieve the data from the DATABASE.
Let’s see the Example with real Json file:
We will use the Reference Service. And we will write the http method in the reference service. That http method should be called in the component methods to get the data or post the data to the REST side. For now will go through with angular services with Json file.Will add one json file in the project. In the angular every request and response will be in the Json only. You need to add the json file in the assets folder under src folder of your project. You may get 404 json file not found, if you add the json file somewhere other than assets location folder.
Json file:
Created the json folder in the assets folder in ‘src/assets’. See example json data.
[ { “id”: 10, "firstName": "Sathish" , "lastName": "Kotha" }, { “id”: 11, "firstName": "Ramesh", "lastName": "Kotha" }, { “id”: 12, "firstName": "Ragav" , "lastName": "Raju" } ]
Employee class:
We need to create the Employee model class. It’s a type of json data, remember every where we need export the class. This model class is a typescript format. Type the below command.
ng g class Employee
This will create the Employee model class in the app folder.
typically you declare types in a model which can then be reused throughout the rest of the application. With TypeScript, frontend applications can now benefit from strongly typed models!
This is pretty straightforward for declaring individual variables,
A simple example of this is a Employee class that defines a firstName and lastName variables that’s are string and an id variable that must be a number:
export class Employee { id: number; firstName: string; lastName: string; }
Service:
In the service, we will import the Http from “@angular/http”; with http we will use the http get the post and request methods. To get the all the methods we need to include the http in the constructor. for more info on http please refer https://angular.io/tutorial/toh-pt6
And import some rxjs. These are reactive extension java script. Rxjs is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or in the server-side using Node.js. We will use some methods from the Rxjs in angular services like map and observable and catch. We will use these in the services.
Don’t instantiated the service with new keyword, it will create error prone and memory leak.
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import { Observable } from 'rxjs/Observable'; import { Employee } from './employee'; @Injectable() export class ReferenceService { constructor(private http: Http) { } getAllEmployees(): Observable< Employee[] > { try { return this.http.get(‘assets/service.json') .map(this.extractdata).catch(this.handleerror) ; // Api Full path like, http://localhost:4200/assets/service.json } catch (error) { console.log(error); } } extractData(res: Response) { const body = res.json(); return body || {}; } handleError(error: any) { return Observable.throw(error); } }
In the above service http reference is used to call the http methods. We created one method is get all employees, we are calling http.get method with json link. This get method will get the json data. Then it will come to map method, it is used to extract the JSON content from the response coming as the observable type. if you got any error while calling the http method it will come to catch method,from there it will directly throw the error with observable throw method.
Component:
Import the reference service in the component as below and one more thing we need the ngOn Init life cycle method. Every component has to implement the ngOnInit method. And this method will call after the constructor. It’s used like a main method. When you come to component, ng On Init method will call, you can call any number of methods in the ngOnInit method.
import { Component, OnInit } from '@angular/core'; import { ReferenceService } from './reference.service'; import { Employee } from './employee'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Angular Service app'; employeesInfo: any; constructor(public referService: ReferenceService) { } getAllEmployeesInfo() { this.referService.getAllEmployees() .subscribe((result: Employee[]) => { console.log('the employess data:' + result); this.employeesInfo = result; }, (error: any) => { console.log('error in employees method'); }); } ngOnInit() { this. getAllEmployeesInfo(); } }
In above component, service method is called in component method getAllEmployeesInfo with reference service http method. And when we got the output it will come to subscribe result. There we are assigning the result to our variables. If we get any error when calling the api it will come to error block. This error will return from catch of Observable throw error.
App.component.html:
<h1 style="text-align: center"> Welcome to {{title}}!</h1> <h3 style="text-align: center">ALL employeesInfo here</h3> <div style="text-align: center;"> <div *ngFor="let emp of employeesInfo"> <b>Emp ID</b> {{emp.id}} <b> First Name is :</b> {{emp.firstName}} <b>Last Name is :</b> {{emp.lastName}}</div> </div>
Above html we are using title in curly brackets. It’s a two way bindings. Whatever we add it automatically convert the value. And one more new word is “*ngFor” structural directives. This is used to iterate the json data in the html. We have the multiple employes the data in the “ employessInfo” variable. So we need to include the ng for here to iterate the data in the html. We add the reference value in the ng for. With that will call the inside object data.
Service used in the Module:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { ReferenceService } from './services/reference.service'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpModule ], providers: [ReferenceService], bootstrap: [AppComponent] }) export class AppModule { }
Above app.module we have imported reference service and app component , All components should be added in the declarations field. And service should go to provides. Httmodule is also imported to imports. And last app component will be added in the bootstrap , bootstrap will added to project from here
if you don’t add the service in the providers you will get following error. One more thing we need to add the http module in the app module imports. Don’t add the http in the imports. If you don’t include. You will get below error.
EXCEPTION: No provider for service!
Clone the repository and install all it’s dependencies:
# Clone repo
git clone https://github.com/Sathishchary/AngularServiceEx
# Enter into directory
cd AngularServiceEx
# Install dependencies
npm install
Angular 4: Component Example
Welcome to the new concept of components in angular 4.
Definition: component is a angular class , Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components.
Components always have a template and only one component can be instantiated per an element in a template.
A component must belong to an NgModule in order for it to be usable by another component or application. To specify that a component is a member of an NgModule, you should list it in the declarations field of that NgModule In app.module file.
we can create the component by using this command.
ng g component ‘component name’
this command will create the component ts file and html and spec.ts and css files with your component name. no need to create the component manually.
Component:
First We need to import the angular Component class from the Angular package: @angular/core
import { Component } from '@angular/core';
we will use this component with the component decorator @component
Component decorator must have the selector and template. if you don’t add these fields component will not valid. because Angular uses the selector to show the html content in the app. You will find the selectors in the chrome console Elements. This selectors will add dynamically to the DOM when your change the routers. The component should have less than 400 lines of code.
Selector : css selector that identifies this component in a template. means we can use the html templates with selector in the application. another advantage is we can use the selector tag any where in the application to show the content of template html, its one of the best feature in Angular.
selector: ‘app’,
Template: inline-defined template for the view. Means it’s the html code, we can write html code in the template, or we can directly give the html src by giving the template url. If we have less html code its easy to add the html content in the template. no need to create another external html file.
template: `{{title}}`,
TemplateUrl: Template url is the external file containing a html template for the view. If we have multiple lines of html content, its better to keep one html file. we can give the html url path in the ‘templateUrl’ field.
templateUrl: ‘./app.component.html’,
Same for styles: css styles we can add two ways by adding styles, styleUrls fields. we should write the styles in the brackets [], it is style guide.
Style: Inline-defined styles to be applied to this component’s view means whatever we write the styles in the component, that css styles applied to html content in template or template Url. If we have less content of styles, we can add the styles in the styles filed.
styles: [‘h1 { font-weight: normal; }’]
styleUrls: list of urls to stylesheets to be applied to this component’s view. If we have multiple styles ,its better to keep the external css files
styleUrls: [‘./app.component.css ]
Component Structure:
import { Component } from '@angular/core'; @Component({ selector: 'app', template: 'Hello <h4>{{title}}</h4> !', styles: [‘h4 { font-weight: normal; }’] }) export class welcome { title: string = 'World'; }
Here component class must add export. then only it will available in the project. we need to add ‘export’ keyword before the component class
Module:
Every Angular app has at least one NgModule class, the root module, conventionally named AppModule. Angular apps are modular and Angular has its own modularity system called NgModules. We will add the components in the ‘declarations’ of this module file.
Import statement for the module:
import { NgModule } from '@angular/core';
NgModule is a decorator to use the ng module.
most important properties are:
- declarations– the view classes that belong to this module.All component class names must add in the declarations. Angular has three kinds of view classes: components, directives, and pipes.
- exports– the subset of declarations that should be visible and usable in the component templates of other modules.
- imports– other modules whose exported classes are needed by component templates declared. We must add the the modules in the ‘imports’ field. whatever we use the modules, that should be place in the imports.
- providers– creators of services that this module contributes to the global collection of services; they become accessible in all parts of the app. These providers are for services. whatever you have services , that services should be add in the provider field. providers will tell to angular how to inject a service.
bootstrap – the main application view, called the root component, that hosts all other app views. Only the root module should set this bootstrap property.
Module Structure:
import { NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; @NgModule({ imports: [ BrowserModule ], providers: [ Logger ], declarations: [ AppComponent ], exports: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
The module declares some objects to be public by marking them with the export key word.
Main.ts:
Launch an application by bootstrapping its root module. During development you’re likely to bootstrap the AppModule in a main.ts file like this one
import { platformBrowserDynamic } from '@angular/platform-browser'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule);
Source code present in the Github
Angular 4: Set up
Angular 4: Set Up
Welcome to Angular Family, It is one of the most power full and faster framework developed by Google. One of its feature is Single Page Application(SPA), It has only one index.html in entire application, Whatever we use all other htmls will include in main index.html. As it is Single Page Application, there is no browser reload. We will get know all the things in the later sections.
Now we will proceed with the installation of angular 4, We will see the basic angular 4 program in Type script.
Angular 4 installation:
Install Node.js
First we need to install the node.js to get access of npm commands.
i) Download it from this site – https://nodejs.org/en/download/
ii) Setup node.js exe file with ‘npm package manager’. After installation done,
Verify that you are running node v4.x.x or higher and npm 3.x.x or higher by running the commands node -v and npm -v in a terminal/console window. Other below node versions will produce errors.
iii) Download the visual studio for better writing angular code from below website.
https://code.visualstudio.com/Download
Install the Angular CLI Globally.
You need to install the angular cli(command line interface) to use the ng command. It will use to create the angular project.
1)Creating a Angular Project
Open a terminal window. Generate a new project by running the below command:
It takes some time to create the project. after creating the project, you need to download the npm packages in your project. Just type cd AngularApp to goto your project location
And type below command to download the dependencies of your package.json file.
you will see the node-modules folder above src folder of your project.
2) Serve the application
Just type the below command in your terminal to launch the server.
The ng serve command launches the server, watches your files, and rebuilds the app as you make changes to those files.
Using the –open (or just -o) option will automatically open your browser on
Your app greets you with a message:
app works!
Your project structure.
Out put:
plunker:
https://embed.plnkr.co/lQ0UOT5XLZoWbogOLokX/