This is a 4 series to help you kickstart your coding in angular 4.

  1. Code Angular – Basic Series- Part 1
  2. Code Angular – Basic Series- Part 2
  3. Code Angular – Basic Series- Part 3
  4. Code Angular – Basic Series- Part 4

This chapter we explore,

  1. how you can create a universal cross-component interaction
  2. how you can search filter to filter result, and using pipe to transform data


What we want to create here?

  

Now, we will create a Favorite/Pin It module.
User can have option to pin and unpin their favorite listing activity.

1) How to globally send and receive message regardless whether relationship is non-sibling, non-parent or non-child components/modules?
In our current modules, we have a listing and details module.


Create favorite component and parked them under list modules.
app/list/favorite.component.html
app/list/favorite.component.ts

Register them in app/list/list.module.ts

  
import { FavoriteComponent } from './favorite.component';  
 @NgModule({
  imports: [ ... ], 
  declarations: [...ListComponent,FavoriteComponent],
  providers: [  ...],
  bootstrap: [ ...]
})
...
..
. 

We update template for html app/list/list.component.html with option to add to fav for pinning it performAddFavorite

  
 <li *ngFor="let activity of fridayActivityList">  
         <a (click)="redirectChooseActivity(activity)" [routerLink]="['/details',  'EXISTING',  activity.id]">   {{activity.activityName }} </a>  
         <a (click)="performAddFavorite(activity)">  [Pin] </a>  
     </li>   

We define template for html app/list/favorite.component.html

  
  <div class="favorite-box">
     <h3>{{title}} </h3> 
     <ol>
         <li *ngFor="let activity of favoriteList">
            {{activity.activityName| uppercase }}
             <a (click)="remove(activity)">[Unpin] </a>
         </li>
     </ol>
 </div>

We should display the list favorited. In each of the list , user can remove the item from the list.

How they are communicating with each other?

   

To gel and connect the communication, we need a service.
We will create CentralService in file app/central.service.ts to act as a centre service center to liaise messages between components.

First we register them in app/list/list.module.ts because the scope applies within this module. To make it, more global , we can register also in app.module.ts

 
import { CentralService } from './central.service';

@NgModule({
  imports: [ ...], 
  declarations: [...],
  providers:[... CentralService] 
})

Create the file app/central.service.ts .

  
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class CentralService {

    // Observable string sources
    private messageSendSource = new Subject();  
    // Observable string streams
    messageSent$ = this.messageSendSource.asObservable();  
    // Service message commands
    announceMessage(mission: string) {
        this.messageSendSource.next(mission);
    }
 
} 

In our case , we will use ListComponent to send message to FavoriteComponent. FavoriteComponent will listen to message from ListComponent.

ListComponent will utilize announceMessage to send a message stream to CentralService.
FavoriteComponent will listen to CentralService for any incoming stream via messageSent$.

The implementation, inside list.component.ts

 
    performAddFavorite(_userSelectedActivity: FridayActivity) {
        this.centralService.announceMessage(_userSelectedActivity);
    }

The implementation, inside favorite.component.ts

 

import { Subscription } from 'rxjs/Subscription';
....
export class FavoriteComponent {
  subscription: Subscription;

    constructor(   private centralService: CentralService, ) { 
      this.subscription = this.centralService.messageSent$.subscribe(
       _userSelectedActivity => {  this.add(_userSelectedActivity); });
    }

    ngOnDestroy() { 
        this.subscription.unsubscribe();
    }
...
}

At beginning lifecycle for the component, it will initialize listening to the centralservice and set it into a variable subscription . At the end of lifecycle , this subscription is destroyed to prevent memory leak.


Now, we will see how we can use filter and pipes.

The format is usually dataPropertyName | pipeName : pipeParameter

In our code you will see |uppercase being used to transformed a data into uppercase without any coding.

   
     <ol>
         <li *ngFor="let activity of favoriteList">
            {{activity.activityName| uppercase }}
             <a (click)="remove(activity)">[Unpin] </a>
         </li>
     </ol> 

This is a built in angular library that transforms a text string to uppercase.
We want to start making a custom pipe that filters the specific activityName in our list.
To make a custom one create file app/list/filter.pipe.ts

   

import {Component,Input,Output,OnInit,ViewChild,EventEmitter,ChangeDetectionStrategy} from '@angular/core';
import {Pipe, PipeTransform} from '@angular/core';   

@Pipe({     name: 'filter' })
export class FilterPipe implements PipeTransform {
    transform(items: any, filter: any): any { 
      //we can loop each key too
     return item && items.filter((item)=>{return item.activityName.match(filter.activityName) ;})
    }
} 

Register in list.module.ts

   
import FilterPipe ... ;
@NgModule({
  imports: [  ], 
  declarations: [  ...FilterPipe  ]  
})

In the html list.component.ts, we add our custom pipe named filter.
We also add parameter json {‘activityName’:’Movie’}

   
*ngFor="let activity of fridayActivityList| filter:{'activityName':'Movie'}"

And then we are done, it is that simple.
Be sure to checkout and refer to plunkr for full implementation.


To start :
Code Angular – Basic Series- Part 1


If you like please share this and comment and subscribe. Feel free to ask any questions or corrections too.

Success is no accident. It is hard work, perseverance, learning, studying, sacrifice and most of all, love of what you are doing or learning to do, Pele

Leave a Reply

Your email address will not be published. Required fields are marked *