Creating Custom Pipe Using Safe HTML In Angular 5

0
681

Introduction: 

We have already seen my articles i.e.,

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.
CoderFunda

To add a new component, use this command –

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.
<p>  
  Below is the speaker info</p>  
<div>  
  <table style="width:36%">  
    <tr style="text-align:left">  
      <th>Name</th>  
      <th>City</th>  
      <th style="width:25%;">Events</th>  
      <th>Expenses</th>  
      <th>Web URL</th>  
    </tr>      
    <tr>  
      <td>Vithal Wadje</td>  
      <td>Mumbai</td>  
      <td><span [innerHTML]="100 | customCssPipe: 100"></span></td>  
      <td>{{1200 | currency : '₹'}}</td>  
      <td>www.CompileMode.com</td>  
    </tr>  
      <tr>  
          <td>Rupesh Kahane</td>  
          <td>Pune</td>  
          <td><span [innerHTML]="80 | customCssPipe: 80"></span></td>  
          <td>{{1000 | currency : '₹'}}</td>  
          <td>www.CoderFunda.com</td>  
      </tr>  
    <tr>  
      <td>Jeetendra Gund</td>  
      <td>Pune</td>  
      <td><span [innerHTML]="90 | customCssPipe: 90"></span></td>  
      <td>{{1100 | currency : '₹'}}</td>  
      <td>www.c-sharpcorner.com</td>  
    </tr>  
    <tr>  
      <td>Amol Patil</td>  
      <td>Pune</td>  
      <td><span [innerHTML]="50 | customCssPipe: 50"></span></td>  
      <td>{{900 | currency : '₹'}}</td>  
      <td>www.c-sharpcorner.com</td>  
    </tr>  
    <tr>  
      <td></td>  
      <td>Total</td>  
      <td> 320 </td>  
      <td>{{4200 | currency : '₹'}}</td>  
      <td></td>  
    </tr>  
  </table>  
<br />  
  <div>Note: Image indicate Speaker is a C-SharpCorner MVP </div>  
</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.
ng g pipe PipeName

I am giving a name as “CustomCss” to the pipe.

ng g pipe CustomCss

After successful creation, the pipe reference will get added into app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
  
import { AppComponent } from './app.component';  
import { RouterModule } from '@angular/router';  
import { HomeComponent } from './Component/home/home.component';  
import { BlogsComponent } from './Component/blogs/blogs.component';  
import { enableProdMode } from '@angular/core';  
import { ContactComponent } from './Component/contact/contact.component';  
import { EventsComponent } from './Component/events/events.component';  
import { CustomCssPipe } from './Pipes/custom-css.pipe';  
  
@NgModule({  
  declarations: [  
    AppComponent,  
    HomeComponent,  
    BlogsComponent,  
    ContactComponent,  
    EventsComponent,  
    CustomCssPipe  
  ],  
  imports: [  
    BrowserModule,  
    RouterModule.forRoot([  
      { path: 'blogs', component: BlogsComponent },  
      { path: 'contact', component: ContactComponent },  
      { path: 'events', component: EventsComponent }  
    ])  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
})  
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.

import { Pipe, PipeTransform } from '@angular/core';  
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';  
  
@Pipe({  
  name: 'customCssPipe'  
})  
  
export class CustomCssPipe implements PipeTransform {  
  
  constructor(private _sanitizer: DomSanitizer) { }  
  
  transform(value: string, event?: number): SafeHtml {  
  
      let termsApply = value + '<span style="color:#b30000;"> <img width="50" alt="MVP Logo" src="./assets/images/MVP.png">  *</span>';  
  
    if (event > 60) {  
      return this._sanitizer.bypassSecurityTrustHtml(termsApply);   
    }  
    else {  
      return this._sanitizer.bypassSecurityTrustHtml(value);  
    }  
  }  
}
  • 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.
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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here