Creating Custom Pipe Using Safe HTML In Angular 5

Introduction

Every application starts out with what seems like a simple task: get data, transform it, and show it to users. Getting data could be as simple as creating a local variable or as complex as streaming data over a WebSocket. A pipe takes in the data as input and transforms it into the desired output. Pipes are declared using @Pipe decorator. We will create a custom pipe here, in this article. Like a filter, a Pipe also takes data as input and transforms it into the desired output.
 
Step 1

First, add one component called events. Go to the "Component" folder and type cmd. Then, hit enter. 
 
 
To add a new component, use this command -
  1. ng g c events  

In events.component.html file, I am going to create one HTML table which contains some information — like Name of speaker, City, Count of Events conducted, Expenses for event, Web URL — and for the time being, I am just adding style into the component.

MVP image is added into src/assets/images folder. 
  1. <p>  
  2.   Below is the speaker info</p>  
  3. <div>  
  4.   <table style="width:36%">  
  5.     <tr style="text-align:left">  
  6.       <th>Name</th>  
  7.       <th>City</th>  
  8.       <th style="width:25%;">Events</th>  
  9.       <th>Expenses</th>  
  10.       <th>Web URL</th>  
  11.     </tr>      
  12.     <tr>  
  13.       <td>Vithal Wadje</td>  
  14.       <td>Mumbai</td>  
  15.       <td><span [innerHTML]="100 | customCssPipe: 100"></span></td>  
  16.       <td>{{1200 | currency : '₹'}}</td>  
  17.       <td>www.CompileMode.com</td>  
  18.     </tr>  
  19.       <tr>  
  20.           <td>Rupesh Kahane</td>  
  21.           <td>Pune</td>  
  22.           <td><span [innerHTML]="80 | customCssPipe: 80"></span></td>  
  23.           <td>{{1000 | currency : '₹'}}</td>  
  24.           <td>www.CoderFunda.com</td>  
  25.       </tr>  
  26.     <tr>  
  27.       <td>Jeetendra Gund</td>  
  28.       <td>Pune</td>  
  29.       <td><span [innerHTML]="90 | customCssPipe: 90"></span></td>  
  30.       <td>{{1100 | currency : '₹'}}</td>  
  31.       <td>www.c-sharpcorner.com</td>  
  32.     </tr>  
  33.     <tr>  
  34.       <td>Amol Patil</td>  
  35.       <td>Pune</td>  
  36.       <td><span [innerHTML]="50 | customCssPipe: 50"></span></td>  
  37.       <td>{{900 | currency : '₹'}}</td>  
  38.       <td>www.c-sharpcorner.com</td>  
  39.     </tr>  
  40.     <tr>  
  41.       <td></td>  
  42.       <td>Total</td>  
  43.       <td> 320 </td>  
  44.       <td>{{4200 | currency : '₹'}}</td>  
  45.       <td></td>  
  46.     </tr>  
  47.   </table>  
  48. <br />  
  49.   <div>Note: Image indicate Speaker is a C-SharpCorner MVP </div>  
  50. </div>  
In the above code, a built-in pipe, i.e., currency, is used which shows a symbol. Also, customCssPipe pipe is used to show MVP image, which indicates that the speaker is an MVP. This is based on the logic that if the event count is greater than 60, then put MVP image and * sign with red color.
 
Step 2

To create a Pipe, first, I am going to add a folder called Pipes in src/app.
 
Syntax to create pipe.
  1. ng g pipe PipeName  
I am giving a name as "CustomCss" to the pipe.
  1. ng g pipe CustomCss  
After successful creation, the pipe reference will get added into app.module.ts file.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. import { RouterModule } from '@angular/router';  
  6. import { HomeComponent } from './Component/home/home.component';  
  7. import { BlogsComponent } from './Component/blogs/blogs.component';  
  8. import { enableProdMode } from '@angular/core';  
  9. import { ContactComponent } from './Component/contact/contact.component';  
  10. import { EventsComponent } from './Component/events/events.component';  
  11. import { CustomCssPipe } from './Pipes/custom-css.pipe';  
  12.   
  13. @NgModule({  
  14.   declarations: [  
  15.     AppComponent,  
  16.     HomeComponent,  
  17.     BlogsComponent,  
  18.     ContactComponent,  
  19.     EventsComponent,  
  20.     CustomCssPipe  
  21.   ],  
  22.   imports: [  
  23.     BrowserModule,  
  24.     RouterModule.forRoot([  
  25.       { path: 'blogs', component: BlogsComponent },  
  26.       { path: 'contact', component: ContactComponent },  
  27.       { path: 'events', component: EventsComponent }  
  28.     ])  
  29.   ],  
  30.   providers: [],  
  31.   bootstrap: [AppComponent]  
  32. })  
  33. export class AppModule { }  
If you see a file named pipe.ts, then the Transform function, which has an actual logic for the pipe, is put on the class.

The first parameter is value which is string, the second is number of events. Import DomSanitizer.
  1. import { Pipe, PipeTransform } from '@angular/core';  
  2. import { DomSanitizer, SafeHtml } from '@angular/platform-browser';  
  3.   
  4. @Pipe({  
  5.   name: 'customCssPipe'  
  6. })  
  7.   
  8. export class CustomCssPipe implements PipeTransform {  
  9.   
  10.   constructor(private _sanitizer: DomSanitizer) { }  
  11.   
  12.   transform(value: string, event?: number): SafeHtml {  
  13.   
  14.       let termsApply = value + '<span style="color:#b30000;"> <img width="50" alt="MVP Logo" src="./assets/images/MVP.png">  *</span>';  
  15.   
  16.     if (event > 60) {  
  17.       return this._sanitizer.bypassSecurityTrustHtml(termsApply);   
  18.     }  
  19.     else {  
  20.       return this._sanitizer.bypassSecurityTrustHtml(value);  
  21.     }  
  22.   }  
  23. }  
  • SafeHtml
    Marker interface for a value that's safe to use as style (CSS).

  • bypassSecurityTrustHtml
    Bypasses the security and trust the given value to be safe style value (CSS).

  • Calling any of the bypassSecurityTrust APIs disables Angular's built-in sanitization for the value passed in. Carefully check and audit all values and code paths going into this call. Make sure that any user data is appropriately escaped for this security context.
Step 3

Now, run the application by using the following command.
  1. ng serve -o  
Now, click on the events menu & you will see the following.
 
 
Summary

In this article, we learned how to create Custom Pipe using safe HTML in Angular 5.