Tag Archives: Angular2

Angular 2 – Pipes passing multiple filters to Pipes

In earlier blog posts we had seen simplistic scenario of using pipes, but what if there is requirement to pass multiple parameters to Pipes in Angular 2,below example demonstrates the same.

Below is the grid for displaying list of persons and as you type in the something in multiple filters like name, email and company, that filter criteria will get applied to that persons data and filter the grid items.

blog-oioe-multiple-params-2

blog-oioe-multiple-params-3

For creating custom pipes you need to create class that implements PipeTransform Interface, this class is then decorated with @Pipe decorator. From the PipeTranform interface you need to implement transform method,  for passing multiple filter parameters to the pipe in the transform method you need to add those parameters like shown below in the code snippet. (nameSearch: string, emailSearch: string, companySearch: string). Transform method implementation then can decide the filtering based on the parameters passed, you can implement your own custom logic over here.

import {Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'personSearch'
})
export class PersonSearchPipe implements PipeTransform {
    transform(items: Array, nameSearch: string, emailSearch: string, companySearch: string){
        if (items && items.length){
            return items.filter(item =>{
                if (nameSearch && item.name.toLowerCase().indexOf(nameSearch.toLowerCase()) === -1){
                    return false;
                }
                if (emailSearch && item.email.toLowerCase().indexOf(emailSearch.toLowerCase()) === -1){
                    return false;
                }
                if (companySearch && item.company.toLowerCase().indexOf(companySearch.toLowerCase()) === -1){
                    return false;
                }
                return true;
           })
        }
        else{
            return items;
        }
    }
}

You need to register the PersonSearchPipe to component module like show below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { PersonSearchPipe } from './personSearch.pipe';
@NgModule({
  declarations: [
    AppComponent,
    PersonSearchPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent],

})
export class AppModule { }

 

In the HTML for the component add the filter like shown below

blog-oioe-multiple-params-1

 

 

Angular 2 Custom Pipes

In Angular 1.x we had used Filters extensively be it inbuilt ones or the custom ones. In Angular 2.x filters have been re-branded/renamed to Pipes. Below is an example for building custom pipes in Angular 2.x.

Below is the grid for displaying list of persons and as you type in the something in search criteria it will apply that filter criteria to person name property and filter the grid items.

personlist

personfilteredlist

For creating custom pipes you need to create class that implements PipeTransform Interface, this class is then decorated with @Pipe decorator. From the PipeTranform interface you need to implement transform method, below is the code snippet for the same.

import {Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'personSearch'
})
export class PersonSearchPipe implements PipeTransform {
    transform(items: Array, searchValue: string){
        if (searchValue){
            return items.filter(item =>{
                if (item.name.indexOf(searchValue) > -1){
                    return true;
                }
                return false;
           })
        }
        else{
            return items;
        }
    }
}

You need to register the PersonSearchPipe to component module like show below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { PersonSearchPipe } from './personSearch.pipe';
@NgModule({
  declarations: [
    AppComponent,
    PersonSearchPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent],

})
export class AppModule { }

 

In the HTML for the component add the filter like shown below

personlisthtml

Attached is the source code over here, to run the source please set up angular-cli and do npm install

Observable’s in Angular 2 (RxJS)

Observables in Angular 2 can be achieved using RxJS(Reactive Extensions for JavaScript). Observables is an ES7 feature so you need to make use of an external library to use it today. RxJS is a library that allows you to work with asynchronous data streams. So what are asynchronous data streams?

  • Asynchronous – we can call a function and register a callback to be notified when results are available, so we can continue with execution and avoid the Web Page from being unresponsive. This is used for ajax calls, DOM-events, Promises, WebWorkers and WebSockets.
  • Data – raw information in the form of JavaScript data types as: Number, String, Objects (Arrays, Sets, Maps).
  • Streams – sequences of data made available over time. Technically everything is stream.

Observables can help manage async data and a few other useful patterns. Observables are similar to Promises but with a few key differences. The first is Observables emit multiple values over time. For example a Promise once called will always return one value or one error. This is great until you have multiple values over time. Web socket/real-time based data or event handlers can emit multiple values over any given time. This is where Observables really shine. Observables are used extensively in Angular 2.

 Observables  Promise
 Observables handle multiple values over time  Promises are only called once and will return a single value
 Observables are cancellable  Promises are not cancellable

The ability of observables being able to handle multiple values over time makes them a good candidate for working with real-time data, events and any sort of stream you can think of. Being able to cancel observables gives better control when working with in-flow of values from a stream. The common example is the auto-complete widget which sends a request for every key-stroke.

RxJS also provides Observable operators which you can use to manipulate the data being emitted. Some of common operators are:

  • Map
  • Filter
  • Take
  • Skip
  • Debounce
  • Retry

So in angular 2 now you services will start returns observables instead of promises like shown below for category service, getCategories returns an observable.

import { Injectable, Inject } from '@angular/core';
import { Http, Response} from '@angular/http';
import { OpaqueToken } from '@angular/core';

import {Category} from './category';
import {Observable} from 'rxjs/Observable';


export let INTERVIEW_APP_CONFIG = new OpaqueToken('app.config');
export interface ApplicationConfiguration{
    apiEndPoint : string,
    timeOut: number
}

export const INTERVIEW_APP_DI_CONFIG: ApplicationConfiguration = {
  apiEndPoint: 'http://app.cloudapp.net/api/Category',
  timeOut: 20
};


@Injectable()
export class CategoryService {
    categoryServiceUrl :string;
    constructor(private http: Http, @Inject(INTERVIEW_APP_CONFIG) config: ApplicationConfiguration){
        console.log(config.apiEndPoint);
        this.categoryServiceUrl = config.apiEndPoint;
    }
       
    getCategories (): Observable<Category[]>{
        console.log("Get Categories");
        return this.http.get(this.categoryServiceUrl)
                        .map(this.extractCategoryData)
                        .catch(this.handleError);
                        
    } 
    
    private extractCategoryData(res: Response){
        let body = res.json();
        return body || { };
    }
    
    private handleError (error: any) {
        let errMsg = (error.message) ? error.message : 
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
  }
}

 

An observable is only enabled when a first observer subscribes. This is a significant difference compared to promises. As a matter of fact, processing provided to initialize a promise is always executed even if no listener is registered. This means that promises don’t wait for subscribers to be ready to receive and handle the response. When creating the promise, the initialization processing is always immediately called.

Observables are lazy so we have to subscribe a callback to let them execute their initialization callback. below component defines the subscribe for the observable which has been returned,

import { Component, OnInit } from '@angular/core';
import { Category } from './category';
import './rxjs-operators';
import { CategoryService, INTERVIEW_APP_CONFIG, INTERVIEW_APP_DI_CONFIG } from './categoryService';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[CategoryService, { provide: INTERVIEW_APP_CONFIG, useValue: INTERVIEW_APP_DI_CONFIG }]
})
export class AppComponent {
  title = 'app works!';
  firstName="Aamol";
  errorMessage: string;
  categories: Category[];
  
 constructor(private categoryService: CategoryService){
   
 }
 ngOnInit(){
   this.getCategories();
   console.log("Getting categories");
  } 
 
 getCategories() {
   this.categoryService.getCategories()
                  .subscribe(
                    categories => this.categories = categories,
                    error => this.errorMessage = <any>error
                  );
 }
}

Observables allow you to register callbacks as shown above, the subscribe method three callbacks as parameters:

  • The onNext callback that will be called when an event is triggered.
  • The onError callback that will be called when an error is thrown.
  • The onCompleted callback that will be called when the observable completes.

Here is the way to register callbacks on an observable:

categoryService.getCategories.subscribe(
  (event) => {
    // handle events
  },
  (error) => {
    // handle error
  },
  () => {
    // handle completion
  }
);

The observable class provides a fromPromise method to create an observable from a promise. This allows you to make a promise part of an asynchronous data stream

Retrying requests – Observable allows you to repeat the source observable sequence the specified number of times or until it successfully terminates. In the context of HTTP requests, this allows you to transparently re-execute requests that failed.

getCategories (): Observable<Category[]>{
        console.log("Get Categories");
        return this.http.get(this.categoryServiceUrl)
                        .retry(4)
                        .map(this.extractCategoryData)
                        .catch(this.handleError);
                        
    } 

Enable RxJS Operators – The RxJS library is quite large. So Angular 2 exposes a stripped down version of Observable in the rxjs/Observable module, a version that lacks most of the operators including map, retry which we have used above, it’s up to us to add the operators we need. We could add every RxJS operators with a single import statement. but we’d pay a penalty in extended launch time and application size because the full library is so big. We only use a few operators in our app.

Instead, we’ll import each Observable operator one-by-one, we’ll put the import statements in one app/rxjs-operators.ts file.

// Statics
import 'rxjs/add/observable/throw';

// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/retry';

Angular 2 – *ngFor – What’s the magic behind * (asterisk) and other mysteries..

In angular 1.* we used to use ng-repeat pretty heavily like

<ul>
    <li ng-repeat="item in items">
        {{item.name}}
    </li>
</ul>

 

Now with angular 2 we achieve same thing with with ngFor

<ul>
    <li *ngFor="let item of items">
        {{item.name}}
    </li>
</ul>

 

The let key is part of the Angular 2 template syntax. let creates a local variable that can be referenced anywhere in our template. So in our case we are creating a local variable let item.

What is this * for?
As you can see there’s no more ng-repeat, it’s ngFor now. why the asterisk? The answer to that is, it’s syntactic sugar. ngFor can only be applied to a <template>. *ngFor is the short form that can be applied to any element and the <template> element is created implicitly behind the scene.  The *  makes it easier to read and write directives that modify HTML layout with the help of templates. NgFor, NgIf, and NgSwitch all add and remove element subtrees that are wrapped in<template> tags.

The HTML template element <template> is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during run time using JavaScript. Think of a template as a content fragment that is being stored for subsequent use in the document.

*ngFor undergoes a transformation like shown below

<ul>
    <li *ngFor="let item of items;" [item]="item"></li>
</ul>

 

Here’s the same after transporting the ngFor to the template directive:

<ul>
    <li template="ngFor let item of items;" [item]="item"></li>
</ul>

And here it is expanded further into a tag wrapping the original element:

 

<ul>
    <template ngFor let-item [ngForOf]="items">
        <li [item]="item">{{item.name}}</li>
    </template>
</ul>

When Angular sees the asterisk (*) in ngFor, it will use its DOM element as template to render the loop.

Moreover *ngFor has more properties i.e index, first, last , even, odd we can get the value of index per iteration, can get the last value or odd, even index too using local variables. here is working example for the same:

<ul>
  <li *ngFor='let item of items #i=index #l=last #e=even '>
    Item value is : {{item}} has index value is : {{i}} and last value is :{{l}} even index :{{e}}</li>
</ul>

 

NgFor provides several exported values that can be aliased to local variables:

  • index will be set to the current loop iteration for each template context.
  • first will be set to a boolean value indicating whether the item is the first one in the iteration.
  • last will be set to a boolean value indicating whether the item is the last one in the iteration.
  • even will be set to a boolean value indicating whether this item has an even index.
  • odd will be set to a boolean value indicating whether this item has an odd index.

Angular 2 also includes the trackBy feature from Angular 1.x that allows performance improvements in our list rendering by tracking a unique identifier on our list items.

<ul>
    <li *ngFor="let item of item; trackBy:item.id;">
        {{$index}} {{item}}
    </li>
</ul>

Angular 2.0 Binding syntax

In angular 2.0 binding syntax has changed a bit. Data binding between component and DOM can be achieved in following manner as shown below, each of these data binding types have specific syntax.

Angular2DataBinding

  • Interpolation – It is one way in from component to DOM. It evaluates expression between 2 curly braces
    <h3>Vehicle Name: {{vehicle.name}}</h3>
    

    They are not editable and the value does not go back to the component. Very useful for read only expressions. What @ property binding to DOM attributes, in older angular we attributes prefixed with ng-* like ng-src etc, this changes in Angular 2.0, it looks some thing like this

    <img [src]="vehicle.imageUrl"/>
    

    You can take any HTML5 property and bind to it. You can bind to custom properties in directives as well. In summary you can bind to element, component or directive property.

  • Event binding – This is reverse flow from DOM to component. Inward data flow from component was denoted with open close square brackets, reverse flow through event bindings from DOM to component is round brackets like show below
    <button (click)="Save()">Save</button>
    

    It executes an expression when and event occurs.

  • Two way data binding – It is value in and value out. For two way binding we have a special directive called ngModel
    <input type="text" [(ng-model)]="vehicle.name"/>
    

    We want to allow value to come in that’s reason we have square bracket and we want passback the updated value to component that’s reason we circular brackets.