Pipes in Angular 2

Developing an Angular 1 application, filters were very useful to accomplish different needs such as filter values from an array, apply a display format to a value and so on.

In Angular 2 filters are non longer availables and the pipes take place.

Instead of filters, angular pipes are more flexible because they are able to accepts parameters as input and returning an output, and can be chained.

In this example we use a pipe to filter an array of objects.

Pipe component

We create a new pipe that will be able to filter a list of customers; in orther to do that, we need to import some stuff:


import { Pipe, PipeTransform } from "@angular/core";
import { Customer } from "./customer.model";

Now we define the Pipe component attributes:


@Pipe({
name: "searchCustomers",
pure: false
})

We defined the pipe selector and a pure attribute to false.

This because we have two types of pipes, pure and impure; a pure pipe is more efficient and fast but is able to detect changes only for primitive values (string, numbers..) or a changed object reference.

Instead, impure pipes can detect any component change; in our case we’ll have an array of customers as input, so we need an impure pipe.

Because the nature of impure pipes, you need to use these components with great care; if you notice a degrade of the performance of the application, it’s possibile to substitute the pipe with a custom component that will do the same work.

This is the code of the pipe:


export class SearchCustomersPipe implements PipeTransform {
transform(customers: Customer[], searchText: string): Customer[] {
let filteredCustomers: Customer[] = new Array<Customer>();

if (customers != undefined) {
filteredCustomers = customers.filter(c => (c.Name.indexOf(searchText) != -1) || (c.Address.indexOf(searchText) != -1));
}

return filteredCustomers;
}
}

The pipe implement the PipeTransform interface and the transform method, that accept two parameter, an array of customers and the text to search as well.

Obviously the method returns the filtered array.

The last step is register the pipe in the application module:


.....

import { SearchCustomersPipe } from "./searchCustomers.pipe";

.....

@NgModule ({

.....
declarations: [
SearchCustomersPipe
]

.....
})

Now the pipe is available to be used in the view.

Customer component

In the view we should have a list of the customers, and we want to filter that typing in a search text field.

The view will look like this:

<table class="table table-striped">
<thead>
<tr>
<th>
{{ "NAME" | translate }}</th>
<th>
{{ "ADDRESS" | translate }}</th>
<th>
{{ "CITY" | translate }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let customer of (customers | searchCustomers: searchText)">
<td>
{{customer.Name}}</td>
<td>
{{customer.Address}}</td>
<td>
{{customer.City.Name}}</td>
</tr>
</tbody>
</table>

We apply the searchCustomers pipe to a customers array (first parameter accepted by the pipe) and after the colon we pass the second parameter searchText.

Here the full Angular2 project.

Pipes in Angular 2

ViewChilds in Angular2

In some cases we enable the communication between a parent and a child component by using parameters passed to the child; or the parent component can waiting an event that will be emitted from the child.

But in other cases the parent need to access to methods of the child component, so we need to use another Angular2 feature, called ViewChild.

In this example we use the ViewChild to show a child component in a modal window from a parent; what we want to do is to show details about the city (city name, zip code, district) from a customer form.

Child component

We need to implement a city component, that has three fields, the name, the zip code and the district.

Starting from the import libraries we have:


import { Component, Input, Output, EventEmitter, OnInit } from "@angular/core";
import { Constants } from "../shared/commons";
import { City } from "./city.model";
import { District } from "./district.model";
import { CityService } from "./city.service";
import { DistrictService } from "./district.service";

........

There’s no news, we have two service for loading cities and districts.

Next, we define the component attributes:


@Component({
 moduleId: module.id,
 selector: "city-detail",
 templateUrl: "city.detail.component.html"
})

The class is look like this:


export class CityDetailComponent {
 @Input() city: City;
 @Output() onSaved = new EventEmitter<City>();
 @Output() onClosed = new EventEmitter();
 public districts: District[];
 public district: District;

constructor(private cityService: CityService, private districtService: DistrictService, private alertService: AlertService) { }

ngOnInit() {
 this.LoadDistricts();
 }

public Save() {
 if (this.district != null) {
 this.districtService.Post(this.district).subscribe(
 (data: District) => {
 this.city.IdDistrict = data.Id;
 this.SaveCity();
 },
 (error) => this.alertService.Error(error));
 }
 else {
 this.SaveCity();
 }

 }

public Close() {
 this.onClosed.emit();
 }

public AddDistrict() {
 this.district = {
 Id: Constants.guidEmpty,
 Name: "",
 Country: ""
 };
 }

private LoadDistricts() {
 this.districtService.GetAll().subscribe(
 (data: District[]) => {
 this.districts = data;
 }
 )
 }

private SaveCity() {
 this.cityService.Post(this.city).subscribe(
 (data) => {
 this.district = null;
 this.onSaved.emit(data);
 },
 (error) => this.alertService.Error(error));
 }
}

Also here no particular news; the component expect an input parameter of type city (the object that needs to be edit) and emit two events, when the detail is saved or when is closed.

Obviously, the parent component will be listen on these events.

We can now implement the view:

<div class="modal-dialog modal-lg">
<div class="modal-content">
<form #cityForm="ngForm" *ngIf="city">
<div class="modal-header">
<h4 class="modal-title">{{ "CITY" | translate }}</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="name">{{ "NAME" | translate }}</label>
<input type="text" name="name" class="form-control" placeholder="{{ 'NAME' | translate }}" [(ngModel)]="city.Name" required
/>
</div>
<div class="form-group">
<label for="address">{{ "ZIP" | translate }}</label>
<input type="number" name="zip" class="form-control" placeholder="{{ 'ZIP' | translate }}" [(ngModel)]="city.Zip" required
/>
</div>
<div class="form-group">
<label for="address">{{ "DISTRICT" | translate }}</label>
<div class="row">
<div class="col-md-4" *ngIf="!district">
<select name="district" class="form-control" [(ngModel)]="city.IdDistrict" required>
<option *ngFor="let d of districts" [ngValue]="d.Id">{{d.Name}}</option>
</select>
</div>
<div class="col-md-1" *ngIf="!district">
<button type="button" class="btn btn-default" (click)="AddDistrict()">{{ 'NEW' | translate }}</button>
</div>
<div class="col-md-4" *ngIf="district">
<div class="form-group">
<label for="name">{{ "NAME" | translate }}</label>
<input type="text" name="name" class="form-control" placeholder="{{ 'NAME' | translate }}" [(ngModel)]="district.Name" required
/>
</div>
<div class="form-group">
<label for="country">{{ "COUNTRY" | translate }}</label>
<input type="text" name="country" class="form-control" placeholder="{{ 'COUNTRY' | translate }}" [(ngModel)]="district.Country"
required />
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" (click)="Save(cityForm)" [disabled]="!cityForm.form.valid">{{ "SAVE" | translate }}</button>
<button type="submit" class="btn btn-default" (click)="Close()">{{ "CLOSE" | translate }}</button>
</div>
</form>
</div>
</div>

The user can select the district from a dropdown list, or insert a new district, specifing a name and the country.

The child component is completed, now we need to render that from the parent component in a modal window.

Parent component

First of all, we’ll using ng2-bootstrap for showing the modal window.

So, in the parent component we need to import some stuff, the ViewChild decorator and the ModalDirective from the ng2-boostrap library.


import { Component, Input, Output, EventEmitter, ViewChild } from "@angular/core";

import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';

In the component class we declare the modal component like this:

export class CustomerDetailComponent {
......
@ViewChild('citiesModal') public citiesModal: ModalDirective;
......
}

The ViewChild decorator needs child component as a paramenter, that can be the component class or a local variable; the view child is of type ModalDirective because we want to show the city detail in a modal window.

Furthermore, we add three methods to the class, the first one is for add  new city, the others are for listen the child events.

export class CustomerDetailComponent {
......
public AddCity() {
 this.city = {
 Id: Constants.guidEmpty,
 IdDistrict: "",
 Name: ""
 };

 this.citiesModal.show();
 }

 onCitySaved(city: City) {
 this.customer.IdCity = city.Id;
 this.city = city;
 this.cities.push(city);
 this.citiesModal.hide();
 }

 onCityClosed() {
 this.city = null;
 this.citiesModal.hide();
 }
......
}

The modal directive has two methods, show and hide, obviously if a new city needs to be added, the modal will be showed, otherwise (save and close events) the modal will be hidden.

The final step is the parent html page, where we add the local variable:

......
<div class="form-group">
<label for="address">{{ "CITY" | translate }}</label>
<div class="row">
<div class="col-md-3">
<select name="city" class="form-control" [(ngModel)]="customer.IdCity" [required]="validationEnabled">
<option *ngFor="let c of cities" [ngValue]="c.Id">{{c.Name}}</option>
</select>
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default" (click)="AddCity()">{{ 'NEW' | translate }}</button>
</div>
</div>
<div bsModal #citiesModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<city-detail [city]="city" (onSaved)="onCitySaved($event)" (onClosed)="onCityClosed($event)"></city-detail>
</div>
</div>
......

The div modal has a bsModal tag that is ng2-boostrap directive and #citiesModal is the local variable specified in the ViewChild declaration above.

In the modal div we have the city detail selector with the respective properties assigned.

Here the full Angular2 project.

ViewChilds in Angular2

Master-detail component in Angular 2

One of the new features of Angular 2 is the communication between components and how they can share informations and events.

It’s very frequent that you have to implement a master/detail view, where you have a list of elements and we need to show the detail when the user click on a row.

Let’s go to implement a parent/child component, such as a customer list and a customer detail.

Customer module

In this module we have a list of the customers, and we need to have CRUD operations.

So, first of all we create the customer.component.ts file and we import the necessary modules:

import { Component, OnInit } from "@angular/core";
import { Customer } from "./customer.model";
import { City } from "./city.model";
import { Constants } from "../shared/commons";
import { CustomerService } from "./customer.service";
.......

We could have other modules used in the component, but it’s not relevant for this topic.

Now we define the component attributes:

@Component({
moduleId: module.id,
selector: "customer",
templateUrl: "customer.component.html"
})

And we start to implement the component class:

export class CustomerComponent implements OnInit {
public customers: Customer[];
public cities: City[];
public customer: Customer;
public edit = false;
public newCustomer = false;

constructor(private customerService: CustomerService, private cityService: CityService, ……) {}

ngOnInit() {
this.Load();
}

public Load() {

this.customerService.GetAll().subscribe(
(data) => {
this.customers = data;
this.customer = null;
this.translateService.get("CUSTOMERSLOADED").subscribe((res: string) => {
this.alertService.Success(res);
});
},
(error) => this.alertService.Error(error));
}
......

}

We inject the dependencies in the constructor and we load the customer list in the OnInit event of the component.

We need two methods for creating/editing of a customer as well:

public New() {
let newCustomer: Customer = {
Id: Constants.guidEmpty,
IdCity: "",
Name: "",
Address: "",
City: null
};

this.customer = newCustomer;
this.edit = true;
}

public Edit(customer: Customer) {
this.customer = customer;
this.newCustomer = false;
this.edit = true;
}

The customer property contains the object and the edit property is used to detect if the customer is in edit mode or not.

We can now implement the view:

<div [hidden]="edit">
<input type="button" class="btn btn-primary" value="New" (click)="New()" />
<table class="table table-striped">
<thead>
<tr>
<th>
{{ "NAME" | translate }}</th>
<th>
{{ "ADDRESS" | translate }}</th>
<th>
{{ "CITY" | translate }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let customer of customers" (click)="Edit(customer)">
<td>
{{customer.Name}}</td>
<td>
{{customer.Address}}</td>
<td>
{{cities | cityName: customer.IdCity}}</td>
</tr>
</tbody>
</table>
</div>

Customer detail component

Now we are ready to implement the detail component.

We import some libraries:

import { Component, Input, Output, EventEmitter } from "@angular/core";
import { Customer } from "./customer.model";
import { CustomerService } from "./customer.service";
import { Constants } from "../shared/commons";
.......

And we define the attributes:


@Component({
 moduleId: module.id,
 selector: "customer-detail",
 templateUrl: "customer.detail.component.html"
})

The component class has some basic methods for the CRUD operations:


export class CustomerDetailComponent {
 @Input() isNew: boolean;
 private currentCustomer: Customer;

 @Input()
 set customer(customer: Customer) {
 this.currentCustomer = customer;
 }

 get customer() {
 return this.currentCustomer;
 }

 constructor(private customerService: CustomerService, private alertService: AlertService, private translateService: TranslateService) {}

 public Save() {
 if (this.isNew) {
 this.customerService.Post(this.customer).subscribe(
 (data) => {
 this.customer = data;
 this.translateService.get("CUSTOMERSAVED").subscribe((res: string) =&amp;gt; {
 this.alertService.Success(res);
 });
 },
 (error) => this.alertService.Error(error));
 }
 else {
 this.customerService.Put(this.customer.Id, this.customer).subscribe(
 (data) => {
 this.translateService.get("CUSTOMERSAVED").subscribe((res: string) =&amp;gt; {
 this.alertService.Success(res);
 });
 },
 (error) => this.alertService.Error(error));
 }
 }

 public Close() {
 }

 public Delete() {
 this.customerService.Delete(this.customer.Id).subscribe(
 () => {
 this.translateService.get("CUSTOMERDELETED").subscribe((res: string) =&amp;gt; {
 this.alertService.Success(res);
 });
 },
 (error) => this.alertService.Error(error));
 }
 }
}

The view look like this:

<form #customerForm="ngForm">
<div class="form">
<button type="submit" class="btn btn-primary" (click)="Save(customerForm)" [disabled]="!customerForm.form.valid">{{ "SAVE" | translate }}</button>
<button type="submit" class="btn btn-danger" (click)="Delete()" *ngIf="!isNew">{{ "DELETE" | translate }}</button>
<button type="submit" class="btn btn-default" (click)="Close()">{{ "CLOSE" | translate }}</button>
<div class="form-group">
<label for="name">{{ "NAME" | translate }}</label>
<input type="text" name="name" class="form-control" placeholder="{{ 'NAME' | translate }}" [(ngModel)]="customer.Name" /></div>
<div class="form-group">
<label for="address">{{ "ADDRESS" | translate }}</label>
<input type="text" name="address" class="form-control" placeholder="{{ 'ADDRESS' | translate }}" [(ngModel)]="customer.Address" /></div>
</div>
</form>

Now we need to implement the communication between the two components.

Communication

In the customer component we add two methods that they will be executed when a customer detail will be closed or deleted:

export class CustomerComponent implements OnInit {
......
onClosed(customer: Customer) {
 this.customer = customer;
 this.edit = false;
 }

onDeleted(customer: Customer) {
 this.customers.splice(this.customers.indexOf(this.customer), 1);
 this.edit = false;
 }
}

These methods will be binded to the events that will happen in the detail component.

In the component view we add the customer detail element:

<customer-detail *ngIf="customer" [hidden]="!edit" [customer]="customer" [isNew]="newCustomer" (onClosed)="onClosed($event)" (onDeleted)="onDeleted($event)"></customer-detail>

Two of the attributes defined in the component selector are the onClosed and onDeleted; so we need to define this properties in the detail component:

export class CustomerDetailComponent {
.......
@Output() onClosed = new EventEmitter<Customer>();
@Output() onDeleted = new EventEmitter<Customer>();
.......
}

The Output keyword means that this is an output property of the component and this property is an EventEmitter with a specific type.

We can now emit this events in the related methods:

export class CustomerDetailComponent {
.......
public Close() {
 this.onClosed.emit(this.customer);
}

public Delete() {
 this.customerService.Delete(this.customer.Id).subscribe(
 () => {
 this.translateService.get("CUSTOMERDELETED").subscribe((res: string) => {
 this.alertService.Success(res);
 });
 this.onDeleted.emit(this.customer);
 },
 (error) => this.alertService.Error(error));
 }
.......
}

We defined these methods above and now we added the emission of the output events; the binded methods of the customer component will be executed.

Here the full Angular2 project.

Master-detail component in Angular 2